Remember a long time ago someone asked me to solve such a thing, one of his C dynamic link libraries has a static variable that automatically increases each time the method is invoked, and he wants to restore the dynamic library dynamically and reload it at a particular time, in order to recover the initial value of the static variable. (This dynamic library cannot be changed)
C # Inside to use dynamic library, need to use DllImport, but this is the global thing, not like the dynamic Load/unload assembly use of the AppDomain method.
This is the thought of Api:loadlibrary, GetProcAddress, and FreeLibrary methods.
[DllImport("kernel32",EntryPoint="LoadLibrary",SetLastError=true)]
static extern IntPtr LoadLibrary(string lpLibName);
[DllImport("kernel32",EntryPoint="GetProcAddress",SetLastError=true)]
static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[DllImport("kernel32",EntryPoint="FreeLibrary",SetLastError=true)]
static extern bool FreeLibrary(IntPtr hModule);
and then call
IntPtr hModule = IntPtr.Zero;
IntPtr pfn = IntPtr.Zero;
// Load the library and get a pointer to the function
hModule = LoadLibrary("ADll.dll");
pfn = GetProcAddress(hModule, "GetValue");
Then the trouble, know the entry address of this function, how do I call this function, I have not known how to solve this in C #, and finally wrote a section of IL code.
.assembly extern mscorlib {}
.assembly Wrapper {}
.class public Wrapper
{
.method public static int32 SomeMethod(native int pfn)
{
.maxstack 2
.locals (int32 V_0)
ldarg.0 // Push pfn onto the execution stack
calli unmanaged stdcall int32()
stloc.0
ldloc.0
ret
}
}
Compile this. Il file into a DLL
And then the code goes on to write
// Make call to function pointer
int i = Wrapper.SomeMethod(pfn);
MessageBox.Show(this, i.ToString());
FreeLibrary(hModule);
The problem is solved.