Get the data out of the emxArray_real_T - c++

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

Related

How to define array size in a struct from an "external" int defined in input

I have a struct with an array in it. The size of this array needs to be 3*input_variable. How can I define a number externally, which is multiplied by an input value, that I can use in a struct to declare the length of an array?
I have tried defining the variable h outside of main as
extern h
then assigning it's value in main from the input variable.
I have also tried to use (in summary)
nt main(int argc, char** argv)
{
int input_variable;
std::cin << input_variable;
int h = input_variable * 3;
void some_function(); // function does some stuff
// with the structs
#ifndef ARRAY_SIZING
#define ARRAY_SIZING h
#endif
return 0;
}
struct _struct_
{
constexpr std::size_t b = ARRAY_SIZING;
double* arr[b];
};
int some_function()
{
// structs are used down here.
return 0;
}
I would love to be able to allocate the size of an array in a struct using an input parameter. Thank you.
Hm. Plain C-arrays in C++. Mostly never needed. OK, you want to interface to a library function.
My guess is that the library does not expect an array, but a pointer. And since your struct contains an array to pointer to doubles, I assume the lib wants to see a double**.
I hardly can imagine that old libraries use references or pointer to arrays, something like:
void function (double* (&array)[10]); // Reference to array
void function (double* (*array)[10]); // Pointer to array
because also here you need an array with a size known at compile time.
I'd rather expect something like
void function (double** array, size_t size); // Pointer to Pointer to double
So, use a std::vector like this:
std::vector<double *> arr(input_variable * 3);
And if you want to hand over the arrays data to the lib functions, then use the vectors data function.
function (arr.data());
You could also create the array with new.
Last hint: Do not use raw pointers.
I hope that I could help a little . . .

coder.ceval struct requires pointer

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

How to have a C++ stack with more than one data type?

Here's the problem:
I am currently trying to create a simple stack-based programming language (Reverse Polish Notation, FORTH style) as a component of a larger project. I have hit a snag, though.
There is no problem with creating a stack in C++ (by using std::vector<>) that would contain one type of element (I could use the syntax std::vector<double> Stack, for instance).
However, a programming language needs to be able to hold multiple data types, such as ints, doubles, strings, and 3D vectors (as in physics vectors with X, Y, and Z components), just to name some simple things.
So, is there a construct in C++ that I could use as a stack that would be able to store more than one kind of primitive type/object/struct?
Sure, one way is to use a tagged union:
enum Type { INTEGER, DOUBLE, /* ... */ };
union Data {
uint64_t as_integer;
double as_double;
// ...
};
struct Value {
Type type;
Data data;
};
The storage for as_integer, as_double, etc. will be overlapped, so a Value structure will take up two words of storage, and your stack will have type std::vector<Value>. Then you access members of data according to the value of type:
void sub(std::vector<Value>& stack) {
// In reality you would probably factor this pattern into a function.
auto b = stack.back();
stack.pop_back();
assert(b.type == INTEGER);
auto a = stack.back();
stack.pop_back();
assert(a.type == INTEGER);
Value result;
result.type = INTEGER;
result.data.as_integer = a.data.as_integer - b.data.as_integer;
stack.push_back(result);
}
Of course, Forths are usually untyped, meaning that the stack consists of words only (std::vector<uint64_t>) and the interpretation of a data value is up to the word operating on it. In that case, you would pun via a union or reinterpret_cast to the appropriate type in the implementation of each word:
void subDouble(std::vector<Data>& stack) {
// Note that this has no type safety guarantees anymore.
double b = stack.back().as_double;
stack.pop_back();
double a = stack.back().as_double;
stack.pop_back();
Data result;
result.as_double = a - b;
stack.push_back(result);
}
void subDouble(std::vector<uint64_t>& stack) {
double b = reinterpret_cast<double&>(stack.back());
stack.pop_back();
double a = reinterpret_cast<double&>(stack.back());
stack.pop_back();
double result = a - b;
stack.push_back(reinterpret_cast<uint64_t&>(result));
}
Alternatively, you can store not values but pointers to instances of a class Value from which other value types such as Integer or Double would derive:
struct Value {};
struct Integer : Value { uint64_t value; };
struct Double : Value { double value; };
// ...
Your stack would have type std::vector<unique_ptr<Value>> or std::vector<Value*>. Then you needn’t worry about different value sizes, at the cost of making wrapper structures and allocating instances of them at runtime.
I would suggest to use the inheritance. Make common base class for the objects you need to store, and make a vector of base types. The store all the inheriting objects in this vector.
Since c++ is an object-orientated language, you might just use inheritance. Here is a quick example taken from http://www.cplusplus.com/forum/general/17754/ and extended:
#include <iostream>
#include <vector>
using namespace std;
// abstract base class
class Animal
{
public:
// pure virtual method
virtual void speak() = 0;
// virtual destructor
virtual ~Animal() {}
};
// derived class 1
class Dog : public Animal
{
public:
// polymorphic implementation of speak
virtual void speak() { cout << "Ruff!"; }
};
// derived class 2
class Cat : public Animal
{
public:
// polymorphic implementation of speak
virtual void speak() { cout << "Meow!"; }
};
int main( int argc, char* args[] )
// container of base class pointers
vector<Animal*> barn;
// dynamically allocate an Animal instance and add it to the container
barn.push_back( new Dog() );
barn.push_back( new Cat() );
// invoke the speak method of the first Animal in the container
barn.front()->speak();
// invoke all speak methods and free the allocated memory
for( vector<Animal*>::iterator i = barn.begin(); i != barn.end(); ++i )
{
i->speak();
delete *i;
}
// empty the container
barn.clear();
return 0;
}
The solution for storing different types is a tagged union
enum Type { INT, STRING, DOUBLE, POINT2D, VECTOR, OBJECT... };
union Data {
int int_val;
double double_val;
struct point2D { int x, int y };
struct { int v3, int v2, int v1, int v0 }; // you can even use unnamed structs
// ...
};
struct StackElem {
Type type;
Data data;
};
In C++ it's even better to use std::variant (or boost::variant in older C++ standards), which might use a tagged union under the hood
However there's no need to use a single stack for all when using the reverse Polish notation. You can use a value stack and a separate operator stack. For every operator on the operator stack you pop the corresponding number of parameters from the value stack. That'll make things easier and save memory since you can use a small char array for operators (unless you need more than 255 operators), and no memory wasted for saving the type as well as the bigger-than-needed data field in the struct like above. That means you don't need a type OPERATOR in the Type enum
You can use a double type stack for all numeric types because a double can contain all int type's range without loss of precision. That's what implemented in Javascript and Lua. If the operator needs more than 1 parameter then just push/pop all of them just like what a compiler does when evaluating a function. You don't need to worry about int operations anymore, just do everything in double, unless there are specific int operators. But you may need different operators for different types, for example + for double addition, p or something like that for vector addition. However if you need 64-bit int then a separate integer type is needed
For example if you need to add 2 3D vectors, push 3 dimensions of the first vector, then the other. When you pop out a vector operator from the operator stack, pop 3 dimensions of the 2 vectors from value stack. After doing the math on it, push resulting 3 dimensions to stack. No need for a vector type.
If you don't want to store int as double then you can use NaN-boxing (or nunboxing/punboxing) like Firefox's JS engine, in which if the value is int then the upper 16 of 64 bits are 1s, otherwise it's double (or pointer, which you probable wouldn't use). Another way is type tag in 3 lower bits in old FFJS engines. In this case it's a little bit complicated but you can use the same operator for every type. For more information about this read Using the extra 16 bits in 64-bit pointers
You can even use a byte array for storing all data types and read the correct number of bytes specified by the operator. For example if the operator indicated that the next operand must be an int, just read 4 bytes. If it's a string, read the 4 bytes of string length first then the string content from the stack. If it's a 2D point of int read 4 bytes of x and 4 bytes of y. If it's a double read 8 bytes, etc. This is the most space efficient way, but obviously it must be traded by speed

Passing struct of array as reference c++

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.

Multiple arrays in a class and XCode

I am trying to use XCode for my project and have this code in my .h:
class FileReader
{
private:
int numberOfNodes;
int startingNode;
int numberOfTerminalNodes;
int terminalNode[];
int numberOfTransitions;
int transitions[];
public:
FileReader();
~FileReader();
};
I get a "Field has incomplete type int[]" error on the terminalNode line... but not on the transitions line. What could be going on? I'm SURE that's the correct syntax?
Strictly speaking the size of an array is part of its type, and an array must have a (greater than zero) size.
There's an extension that allows an array of indeterminate size as the last element of a class. This is used to conveniently access a variable sized array as the last element of a struct.
struct S {
int size;
int data[];
};
S *make_s(int size) {
S *s = (S*)malloc(sizeof(S) + sizeof(int)*size);
s->size = size;
return s;
}
int main() {
S *s = make_s(4);
for (int i=0;i<s->size;++i)
s->data[i] = i;
free(s);
}
This code is unfortunately not valid C++, but it is valid C (C99 or C11). If you've inherited this from some C project, you may be surprised that this works there but not in C++. But the truth of the matter is that you can't have zero-length arrays (which is what the incomplete array int transitions[] is in this context) in C++.
Use a std::vector<int> instead. Or a std::unique_ptr<int[]>.
(Or, if you're really really really fussy about not having two separate memory allocations, you can write your own wrapper class which allocates one single piece of memory and in-place constructs both the preamble and the array. But that's excessive.)
The original C use would have been something like:
FileReader * p = malloc(sizeof(FileReader) + N * sizeof(int));
Then you could have used p->transitions[i], for i in [0, N).
Such a construction obviously doesn't make sense in the object model of C++ (think constructors and exceptions).
You can't put an unbound array length in a header -- there is no way for the compiler to know the class size, thus it can never be instantiated.
Its likely that the lack of error on the transitions line is a result of handling the first error. That is, if you comment out terminalNode, transitions should give the error.
It isn't. If you're inside a struct definition, the compiler needs to know the size of the struct, so it also needs to know the size of all its elements. Because int [] means an array of ints of any length, its size is unknown. Either use a fixed-size array (int field[128];) or a pointer that you'll use to malloc memory (int *field;).