Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

P/Invoke and unmanaged DLL state

Tags:

c

.net

pinvoke

I have an assembly and an unmanaged DLL. I tried to use a static variable in the unmanaged DLL but it does not seem to survive between calls from the assembly.

I wonder whether static variables in unmanaged DLLs can exist between P/Invoke calls, possibly I miss something in my code. If not, what is the best way to store a state for such an unmanaged DLL if a global static variable is not an option?

like image 249
Centro Avatar asked May 17 '11 11:05

Centro


1 Answers

The .Net runtime will typically not unload your pinvoke DLLs on its own, as it has no way of knowing if its safe to do so, like if they contain state, including and globals like static strings or whatever.

Its not clear in you question wether you mean a static on the .Net side or a static / const on the unmanaged side. If you mean one on the managed side, then its not guarenteed to exist after the call comes back, if its been marshaled, and depending on the setup for the call on the managed side unless you follow some very specific rules. If its just a plan number then it doesnt matter so I'm going to assume its a string or someother more complex structure.

As an example, if the callee is a c function in a dll that expects a ansi string, and you let pinvoke take a C# string, it will marshal the c# unicode string to an asni string for you, and will expect to get to reclaim that memory after the call is done, even if that string came from a C# static. Even if that wasnt the case, any pointer to managed memory should be considered invalid after the call unless you are pinning that memory.

Here is some rope to hang yourself :) Use this with care. This will anchor managed memory indefinately, and I woulodnt suggest doing this. The DLL having its own copy of a string, or managed side having its own copy, wouldnt be the greatest programming crime ever committed. And as a practical matter would be much faster if they each have one in thier own heap, if it is indeed intended to be static. The C function needs to make its own copy before the call returns.

like image 52
Celess Avatar answered Sep 17 '22 17:09

Celess