Monday, November 30, 2009

How to use an unmanaged DLL from another location

//[DllImport("someDll.dll")]
//private static extern uint someMethod(string s);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate uint someMethod(string s);


[DllImport("kernel32.dll", SetLastError=true)]
private static extern IntPtr LoadLibrary(string dllToLoad);

[DllImport("kernel32.dll")]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

[DllImport("kernel32.dll")]
private static extern bool FreeLibrary(IntPtr hModule);


private static IntPtr libSomeDll;
private static IntPtr addrSomeMethod;


libSomeDll = LoadLibrary(Path.Combine(path, "someDll.dll"));
if (libSomeDll == IntPtr.Zero)
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "LoadLibrary failed for someDll.dll.");
}

addrSomeMethod = GetProcAddress(libSomeDll, "someMethod");
if (addrSomeMethod == IntPtr.Zero)
{
throw new ApplicationException("GetProcAddress failed for someMethod.");
}


someMethod methSomeMethod = (someMethod)Marshal.GetDelegateForFunctionPointer(addrSomeMethod, typeof(someMethod));
uint result = methSomeMethod("");

bool result2 = FreeLibrary(libSomeDll);

1 comment:

オテモヤン said...
This comment has been removed by a blog administrator.