P / Invoke and Unmanaged DLL

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

I wonder if static variables exist in unmanaged DLLs between P / Invoke calls, maybe I missed something in my code. If not, what is the way to maintain state for such an unmanaged DLL if the global static variable is not an option?

+6
source share
2 answers

. .NET runtime will usually not unload your pinvoke dll files on its own, as it does not know how safe it is, for example, if they contain state, including global values ​​such as static strings or something else.

It is not clear what you doubt, you mean static on the .Net side or static / const on the unmanaged side. If you mean one on the managed side, then it should not exist after the call returns, if it has been marshaled, and depending on the setting for the call on the managed side, if you do not follow some very specific rules. If it’s just a plan number, then it doesn’t matter, so I'm going to assume its line or other more complex structure.

As an example, if the function being called is an ac function in a dll that expects ansi string and you let pinvoke take a C # string, it will march the C # unicode string for the asni string for you and will expect to get to return this memory after the call even if this line came from a static C # element. Even if this is not the case, any pointer to managed memory should be considered invalid after the call, unless you freeze this memory.

Here are a few ropes to hang yourself :) Use this with caution. This will fix managed memory indefinitely, and I suggest doing it. A DLL with its own copy of a string or a managed party having its own copy will not be the biggest programming crime that has ever been committed. And as a practical matter, it will be much faster if each of them has its own heap, if it is really designed for static. Function C must make its own copy before returning the call.

+1
source

This type of state depends entirely on unmanaged code, but it depends on what static variables do to it, as soon as you call it, you have no control over it and are bound by library rules in the question.

One commenter suggests deleting static information by unloading the library that contains it, this is impossible in all cases (you cannot unload the main library c), but it can work for you.

0
source

Source: https://habr.com/ru/post/888309/


All Articles