Reputation: 103
I try to import functions from my C-Dll. A function has a struct array as a parameter. The struct will be filled in the function.
struct test
{
int test1;
int test2;
};
void FillStruct( struct test stTest[], int size)
{
if(size == 2){
stTest[0].test1 = 5;
stTest[0].test2 = 5;
stTest[1].test1 = 2;
stTest[1].test2 = 2;
}
}
The method FillStruct
should be used in C#.
I think I have to create the struct in C#. Must I marshal the struct if I use memcpy
in the Fillstruct
?
Upvotes: 1
Views: 640
Reputation: 2603
struct Test
{
public int test1;
public int test2;
}
[DllImport("mydll", CallingConvention = Cdecl)]
public static extern void FillStruct( Test[] stTest, int size);
[...]
var test = new Test[n];
FillStruct(test, test.Length);
I don't see the problem here. It does not matter what you do with the memory in your c code: as long as you don't cause buffer overflows, you can read, write an copy all you want. c# arrays are just the type and length of the array, followed by the data. When you use p/invoke with simple structs, a pointer to the first element in the original array will be passed to your c code.
Upvotes: 2