Question:
I am working on to use a C library in C#. Library is the globalplatform by kaoh, here is the github link.What I have done is compiled the C library into a shared library (DLL) by following these steps written in the readme.
dllimport
in my C# code and successfully called some of the library functions.But then I hit a problem when trying to call a certain function that have a specific struct as its parameter. The problem is, its members value in the C side is differs from what it have been assigned in C# side.
I decided to do some testing by replicating the same struct then printing its members value. Here I created two structs which is identical to the struct that causing the problem:
Now, for the C#. First, I created a C# library project and did the prototyping/signature/marshalling as follow :
Finally, this is what I got:
Why is the ZEN members have incorrect value but the MYARRAYSTRUCT members is correct?
Any suggestion to fix this?
Answer:
The problem is that you declareZEN
in your C# as class
. This makes it a reference type. And so when you pass ZEN
as ref
then you pass a pointer to a pointer to the structure. That’s one level of indirdction too many.By contrast you declared
MYARRAYSTRUCT
as struct
, a value type. When you pass this as ref
, you pass a pointer to the structure.Change
ZEN
to be declared as struct
.If you have better answer, please add a comment about this, thank you!