I have an external c-function I need to call, and I wish to use ForeignFunctionLoad.
The c-function, foo, takes as an argument a reference to a struct, for example:
foo(int v, struct * myStruct);
myStruct itself contains an array, i.e. like
typedef struct {
double a;
double b[2][2];
} myStruct;
How can I call this function foo?
One can probably load it correctly in this way:
fooInMathematica = ForeignFunctionLoad["mylibfile","foo",{"CInt",RawPointer::[{"CDouble",RawPointer::["CDouble"]}]}];
But when I call it, I need to provide a pointer to some memory allocated via RawMemoryAllocate. So I could do so by creating
structInMathematica = RawMemoryAllocate[{"CDouble", "RawPointer"::["CDouble"]}];
However, this call does not know the size of the array of doubles, and would allocate a double and a pointer to a double - while the function needs the array, and would write into the 4 elements of the array. I can, of course allocate an array of 4 doubles via
arrayInMathematica = RawMemoryAllocate["CDouble",4];
But I would need to somehow "nest" the two, i.e. the array lives inside the struct.
Any idea?
Thank you!
Stefan
ForeignFunctionLoad
looks interesting, but every API has to have some limits. I think you would be better off by writing a wrapper functions withLibraryLink
. For example, this wrapper copies some data from mathematica to the struct and then calls the functionfoo
. $\endgroup$p
points, then you might try to callfoo
this way:foo( v, reinterpret_cast< myStruct *>(p) )
. Whether that works or not might depend on the compiler that produced the library. IIRC, the C standard does not mandatestructs
to be packed, so the compiler is allowed to put in some padding. (It might try to put the arrayb
onto a specially aligned address in order to further vectorization.) And different compiler might have different strategies to this. $\endgroup$