C# to unmanaged dll data structures interop

Posted by Shane Powell on Stack Overflow See other posts from Stack Overflow or by Shane Powell
Published on 2010-05-18T19:17:59Z Indexed on 2010/05/18 19:20 UTC
Read the original article Hit count: 229

Filed under:
|
|

I have a unmanaged DLL that exposes a function that takes a pointer to a data structure. I have C# code that creates the data structure and calls the dll function without any problem. At the point of the function call to the dll the pointer is correct.

My problem is that the DLL keeps the pointer to the structure and uses the data structure pointer at a later point in time. When the DLL comes to use the pointer it has become invalid (I assume the .net runtime has moved the memory somewhere else).

What are the possible solutions to this problem?

The possible solutions I can think of are:

  • Fix the memory location of the data structure somehow? I don't know how you would do this in C# or even if you can.
  • Allocate memory manually so that I have control over it e.g. using Marshal.AllocHGlobal
  • Change the DLL function contract to copy the structure data (this is what I'm currently doing as a short term change, but I don't want to change the dll at all if I can help it as it's not my code to begin with).

Are there any other better solutions?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about c#