• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Incorrect struct members value when passing the struct reference from C# to C

Resolved: Incorrect struct members value when passing the struct reference from C# to C

0
By Isaac Tonny on 18/06/2022 Issue
Share
Facebook Twitter LinkedIn

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.
I used 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:
For printing its member value, I add these functions in the C library:
I used pass by pointer to pass the struct, replicating the function that causing the problem.
Now, for the C#. First, I created a C# library project and did the prototyping/signature/marshalling as follow :
Then, call the C# library above via console project, as follow:
Both C# library and C# console are set to use x86 as its platform target. (Project>Properties>Build>Platform targer: x86)
Finally, this is what I got:
The ZEN members value seems to be assigned with random value and it changes every time its compiled.
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 declare ZEN 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!

c#
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Using AWK to count multiple patterns in a file

01/04/2023

Resolved: significance letter above bar graphic in wrong order

01/04/2023

Resolved: VBA – Applying border around the areas with value/text

01/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.