I am using some external C++ code from within Matlab by calling it via coder.ceval:
coder.ceval('myCppFuncName', coder.wref(mySruct))
This works perfectly as long as myStruct is something simple as
myStruct.a = 0;
myStruct.b = 1;
Now I have a struct which is defined in the C++ header file struct.h:
typedef struct
{
double x;
double y;
} myPoint;
typedef struct
{
int num_points;
myPoint *points; // pointer to array of myPoint-structs
} myStruct;
I don't know how to represent the pointer of the C++ struct in Matlab. As I need to define the struct in Matlab I am trying things like:
coder.cstructname(matlab_myPoint,'myPoint','extern');
coder.cstructname(matlab_myStruct,'myStruct','extern');
matlab_myPoint= struct('x',0,'y',0);
matlab_myStruct = struct('num_points',2,'points',myPoint);
ending in an error message
error C2440: '=' : cannot convert from 'myPoint' to 'myPoint *'
In the original C++ struct, a Pointer to an array of structs is used. How can I reproduce this relationship in a Matlab-born struct ? Thank you!
I could finally solve the issue by not passing objects or pointer to objects from Matlab to C but handing over structs instead. The struct in my case contains all the data I need to initialize a new object of the desired class in c.
In order to achieve this one needs to use the same struct architecture in Matlab and in C.
Then with
coder.cstructname(matlab_struct_name,'c_struct_name','extern');
one tells the compiler which C struct is defined by which Matlab struct. The C-Header file has to be specified in the Simulink properties.
The call of the C-Code in Matlab finally looks like this:
coder.ceval('gateway', 1, coder.ref(matlab_struct_name), ,coder.wref(matlab_myRet));
where matlab_myRet has been created the same way like matlab_struct_name and represents the return value struct. All values which are written to it inside the C-Code can later be obtained within Matlab:
matlab_myRet.x(1:5);
matlab_myRet.y(1:5);
Finally an example of the used struct:
in Matlab:
matlab_struct_name.x = 123;
matlab_struct_name.y = 456;
matlab_myRet.x = zeros(10,1);
matlab_myRet.y = zeros(10,1);
in C-Code (header):
typedef struct
{
double x[5];
double y[5];
}matlab_struct_name;
typedef struct
{
double x[10];
double y[10];
}myReturn;
Hope this helps
Related
I want to know whether we can memcpy a structure containing 2 float variables into another structure containing 2 int variable. This is what I have wriiten so far
struct stFloat
{
float a;
float b;
};
struct stInt
{
int a;
int b;
};
int main()
{
struct stFloat aa;
aa.a=12.234;
aa.b=673.797;
struct stInt bb;
memcpy(&bb,&aa,sizeof(stFloat));
printf("%d %d\n",bb.a,bb.b);
return 0;
}
But unfortunately I am not getting the desired result. The output that I was expecting is 12 673 but the output looks like some garbage. Can somebody help me resolving this issue.
Thanks
Integer and float have different internal representation, and memcpy is simply a bitwise copy so if you were expecting the numbers to be converted in some way it's not going to happen.
Instead you need to do it yourself, for example by declaring a constructor or function or assignment operator that allows you to assign stfloats to stint. This also allows you to explicitly indicate the conversion you want.
In general it is a bad idea to use memcpy (among other things, because it only works for PODs, and also because you get this sort of problem). It's a C thing that should be avoided in C++.
No, you can't, but you can write a function which will do it for you :
void cpy(struct stFloat *src, struct stInt *dest){
dest->a = (int)src->a;
dest->b = (int)src->b;
}
then, call it by passing your structures by references pointer (else it will only work on copies of the structures) :
struct stFloat f;
struct stFloat i;
cpy(&f,&i);
I have converted a simple code to C++ using Matlab coder. However, my main problem is that I cannot get its output! How can I convert the output which is an emxArray_real_T type to a C++ array and print it?
C Code Interface for Dynamically Allocated Arrays
In generated code, MATLAB represents dynamically allocated data as a
structure type called emxArray. An embeddable version of the MATLAB
mxArray, the emxArray is a family of data types, specialized for all
base types. emxArray Structure Definition
typedef struct emxArray_<baseTypedef> {
<baseType> *data;
int *size;
int allocatedSize;
int numDimensions;
boolean_T canFreeData;
} emxArray_<baseTypedef>;
baseTypedef is the predefined type in rtwtypes.h corresponding to
baseType. For example, here is the definition for an emxArray of base
type double with unknown upper bounds:
typedef struct emxArray_real_T {
double *data; //<<<<<<<<<<<<<<< RIGHT HERE
int *size;
int allocatedSize;
int numDimensions;
boolean_T canFreeData;
} emxArray_real_T;
The predefined type corresponding to double is real_T. For more
information on the correspondence between built-in data types and
predefined types in rtwtypes.h
http://www.mathworks.com/help/fixedpoint/ug/c-code-interface-for-unbounded-arrays-and-structure-fields.html?refresh=true
I am new to structure programming, and I find it quite confusing when trying to pass a structure of array in c++. I have a project to do for college, a Star Trek game. This is the sample code:
void main_menu(char,char [][sz2],int&,struct enterpriseSt*,struct klingonSt*[100]);
void combat_menu(char [][sz2],struct enterpriseSt*,int&,struct klingonSt*[100]);
struct enterpriseSt
{
int energy_level;
int damage;
int torpedo_count;
};
struct klingonSt
{
int energy_level;
int damage;
int position[2];
};
int main()
{
struct enterpriseSt enterprise;
enterprise.energy_level=energy_ent_max;
enterprise.damage=0;
enterprise.torpedo_count=10;
struct klingonSt klingon[100];
main_menu(command,galaxy,turn,&enterprise,&klingon);
return 0;
}
void main_menu(char command, char galaxy[][sz2],int& turn,struct enterpriseSt * enterprise,struct klingonSt * klingon[100])
{
combat_menu(galaxy,enterprise,turn,klingon);
}
I have two structures, enterpriseSt and klingonSt. I can pass enterprise no problem, but with klingon I am struggling. I get all kinds of errors, doesn't matter what combination I use. The current one is:
error: cannot convert ‘klingonSt (*)[100]’ to ‘klingonSt**’ for argument ‘5’ to ‘void main_menu(char, char (*)[64], int&, enterpriseSt*, klingonSt**)’
I've made such a mess with it now. Could someone please explain it to me why it works with enterprise but not with klingon?
I use g++ compiler on Ubuntu. Thanks.
Your problem is in misunderstanding the arguments parsing rules.
you think that struct klingonSt*[100] is a pointer to the array of size 100 of type struct klingonSt, but actually when argument parsing, array and function symbols that should be situated on the right of token has higher priority, than symbols on the left of expression.
So, lets first write the expression with argument name included:
struct klingonSt*var[100]
and parse it
var
is an array of size 100 (as array symbol on the right has higher priority, than pointer on the left)
of pointers
to the type struct klingonSt
so, struct klingonSt*var[100] is actually is array of size 100 of pointers to struct klingonSt.
to pass a pointer to the array of size 100 of type struct klingonSt you should change parsing precedence using parenthesis:
struct klingonSt(*var)[100]
or
struct klingonSt(*)[100]
If you change your definition, your code will compile fine.
I think you're a bit confused on passing arrays to functions. When this is done, the array decays into a pointer to the first element of the array. You can declare the parameter as an array, but the array range is ignored by the compiler, and not enforced at runtime. Thus, for this style of coding, you'd just want to pass the array as a pointer, and length as a separate parameter (I've omitted your other params for clarity):
void main_menu(enterpriseSt*, int enterpriseCount, klingonSt*, int klingonCount);
Some alternatives to consider:
Adopting a modern C++ style, and use std containers like vector/list, passing them by reference.
void main_menu(vector<enterpriseSt> & enterprises, vector<klingonSt> & klingons);
Or, using a template wrapper to pass sized local arrays implicitly:
template<size_t eCount, size_t kCount>
void main_menu(enterpriseSt (&enterprises)[eCount], klingonSt (&klingons)[kCount])
{
main_menu(enterprises, eCount, klingons, kCount);
}
The problem that
struct klingonSt * klingon[100]
is an array of 100 struct klingonSt * rather than a point to 100 struct klingonSt
use struct klingonSt klingon[][100] instead.
I am using gcc version 4.3.3 on my Ubuntu (i686). I have written a stripped down test program to describe my lack of understanding and my problem. The program shall tell me the size of the struct, which I implemented. So I have a typedef struct for a Message and a little main to play around:
#include <stdio.h>
typedef struct {
int size;
enum {token=0x123456};
} Message;
int main(int argc, char * argv[])
{
Message m;
m.size = 30;
printf("sizeof(int): %d\n",sizeof(int));
printf("sizeof(0x123456): %d\n",sizeof(0x123456));
printf("sizeof(Message): %d\n",sizeof(Message));
printf("sizeof(m): %d\n",sizeof(m));
}
While compiling this source with gcc I get the following warning, which I don't understand:
$ gcc sizeof.c
sizeof.c:5: warning: declaration does not declare anything
Line 5 refers to the enum line. I want that token in every Message, that I create. What am I doing wrong? What do I have to change to get rid of that warning?
My main contains several calls of sizeof(). When I run the program, you can see in the output that the integer has the size of four, the hex number has the size of 4, but the typedef struct Message has the size of 4, too:
$ ./a.out
sizeof(int): 4
sizeof(0x123456): 4
sizeof(Message): 4
sizeof(m): 4
That is very confusing to me. Why has Message the size of 4, although it contains an integer and an integer within an enum, each with the size of 4. If the sizeof(Message) would be at least 8, it would be logical to me.
But why is it only 4? How do I get the real size in Bytes of my Message? Or is this really the real size? If so, why?
Is there a difference in getting the size of a Message between C and C++?
An enumeration doesn't actually need any space, it's just a way for the compiler to recognize a set of literal numbers by a name.
You are not declaring anything with:
enum {token=0x123456};
Your declaration is similar to:
typedef struct {
int size;
int;
} Message;
If you declare your struct like this:
typedef struct {
int size;
enum {token=0x123456} e;
} Message;
There will be two fields, but e will not be initialized to anything. You need to set it manually for every instance: message.e=token.
The correct way to achieve what you want is, to use constructors in C++:
struct Message {
int size;
int token;
Message() : token(0x123456) {};
};
Or non-static data member initializers in C++11:
struct Message {
int size;
int token=0x123456;
};
There is no way to initialize field in struct declaration in C.
Line 5 does not declare any variable that is of type enum. So the compiler does the only thing it can do: ignore it.
If you want to create a member of that type in the struct, write something like
enum {token=0x123456} thetoken;
But be aware that this field can only have one valid value, is that what you want?
Edit:
Oh, and to answer your other question: I can't see a difference in output when compiling as C or C++. But there is a difference between how how you should write struct definitions.
typedef struct {
int size;
enum YouShouldDeclareAName {token=0x123456};
} Message;
your enum is a subclass/subtype of your Message struct, therefore bounds to Class and not object. Like a namespace. You do not create any variable with it.
Change it to:
typedef struct {
int size;
enum YouShouldDeclareAName {token=0x123456} token;
//or
YouShouldDeclareAName token2;
} Message;
You've defined a constant Message::token that's shared between all objects. Since it's shared, it doesn't count towards the size of a single object.
As the others answers note, you've declared an enumerated type, you just happened to do it inside a structure instead of at global scope. There's nothing to store, so it uses no memory.
Now if you were to declare an instance of your enumeration in that structure...
typedef struct {
int size;
enum {token=0x123456} e;
} Message;
int main(int argc, char * argv[])
{
Message m;
m.size = 30;
printf("sizeof(m): %d\n",sizeof(m));
}
sizeof(m): 8
Press any key to continue . . .
LINE 5:
enum {token=0x123456};
This line doesn't define any enum variable, its a declaration, because of this your compiler complains about line 5 saying its only a declaration.
proper usage should be:
enum {xyz=5} enum_variable_name;
Only then the compiler will allocate space for this.
Just like class, function, enum, static menber doesn't store in the object space!
In C/C++, how do I determine the size of the member variable to a structure without needing to define a dummy variable of that structure type? Here's an example of how to do it wrong, but shows the intent:
typedef struct myStruct {
int x[10];
int y;
} myStruct_t;
const size_t sizeof_MyStruct_x = sizeof(myStruct_t.x); // error
For reference, this should be how to find the size of 'x' if you first define a dummy variable:
myStruct_t dummyStructVar;
const size_t sizeof_MyStruct_x = sizeof(dummyStructVar.x);
However, I'm hoping to avoid having to create a dummy variable just to get the size of 'x'. I think there's a clever way to recast 0 as a myStruct_t to help find the size of member variable 'x', but it's been long enough that I've forgotten the details, and can't seem to get a good Google search on this. Do you know?
Thanks!
In C++ (which is what the tags say), your "dummy variable" code can be replaced with:
sizeof myStruct_t().x;
No myStruct_t object will be created: the compiler only works out the static type of sizeof's operand, it doesn't execute the expression.
This works in C, and in C++ is better because it also works for classes without an accessible no-args constructor:
sizeof ((myStruct_t *)0)->x
I'm using following macro:
#include <iostream>
#define DIM_FIELD(struct_type, field) (sizeof( ((struct_type*)0)->field ))
int main()
{
struct ABC
{
int a;
char b;
double c;
};
std::cout << "ABC::a=" << DIM_FIELD(ABC, a)
<< " ABC::c=" << DIM_FIELD(ABC, c) << std::endl;
return 0;
}
Trick is treating 0 as pointer to your struct. This is resolved at compile time so it safe.
You can easily do
sizeof(myStruct().x)
As sizeof parameter is never executed, you'll not really create that object.
Any of these should work:
sizeof(myStruct_t().x;);
or
myStruct_t *tempPtr = NULL;
sizeof(tempPtr->x)
or
sizeof(((myStruct_t *)NULL)->x);
Because sizeof is evaluated at compile-time, not run-time, you won't have a problem dereferencing a NULL pointer.
In C++11, this can be done with sizeof(myStruct_t::x). C++11 also adds std::declval, which can be used for this (among other things):
#include <utility>
typedef struct myStruct {
int x[10];
int y;
} myStruct_t;
const std::size_t sizeof_MyStruct_x_normal = sizeof(myStruct_t::x);
const std::size_t sizeof_MyStruct_x_declval = sizeof(std::declval<myStruct_t>().x);
From my utility macros header:
#define FIELD_SIZE(type, field) (sizeof(((type *)0)->field))
invoked like so:
FIELD_SIZE(myStruct_t, x);