I need to return a list of points i have from a C dll to a C# application using PInvoke. These are points in 3 dimensions [x,y,z]. The number of points varies by what kind of model it is. In C i handle this a linked list of structs. But I don’t see how i can pass this on to C#.
The way I see it, I have to return a flexible two dimensional array, probably in a struct.
Any suggestions to how this can be done? Both ideas on how to return it in C and how to access it in C# are highly appreciated.
A linked list of structs could be passed back, but it would be quite a hassle to deal with, as you would have to write code to loop through the pointers, reading and copying the data from native memory into managed memory space. I would recommend a simple array of structs instead.
If you have a C struct like the following (assuming 32-bit ints)…
… then you’d represent it nearly the same way in C#:
Now to pass an array back, it would be easiest to have your native code allocate the array and pass it back as a pointer, along with another pointer specifying the size in elements.
Your C prototype might look like this:
The P/Invoke declaration would then be this:
The
MarshalAsattribute specifies that the array should be marshaled using the size specified in the second parameter (you can read more about this at MSDN, “Default Marshaling for Arrays”).If you use this approach, note that you must use
CoTaskMemAllocto allocate the native buffer as this is what the .NET marshaler expects. Otherwise, you will get memory leaks and/or other errors in your application.Here is a snippet from the simple example I compiled while verifying my answer:
The managed caller can then deal with the data very simply (in this example, I put all the interop code inside a static class called
NativeMethods):