Dynamic loading DLLs in C #

Source: Internet
Author: User
Tags wrapper

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.