Last active
March 25, 2017 09:54
-
-
Save haroldcris/c743a3d38613c73ce874ff650d6d6584 to your computer and use it in GitHub Desktop.
Register DLL from C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Registrar : IDisposable | |
{ | |
private IntPtr hLib; | |
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] | |
internal static extern IntPtr GetProcAddress(IntPtr hModule, string procName); | |
[DllImport("kernel32.dll", SetLastError = true)] | |
internal static extern IntPtr LoadLibrary(string lpFileName); | |
[DllImport("kernel32.dll", SetLastError = true)] | |
internal static extern bool FreeLibrary(IntPtr hModule); | |
internal delegate int PointerToMethodInvoker(); | |
public Registrar(string filePath) | |
{ | |
hLib = LoadLibrary(filePath); | |
if (IntPtr.Zero == hLib) | |
{ | |
int errno = Marshal.GetLastWin32Error(); | |
throw new Win32Exception(errno, "Failed to load library."); | |
} | |
} | |
public void RegisterComDLL() | |
{ | |
CallPointerMethod("DllRegisterServer"); | |
} | |
public void UnRegisterComDLL() | |
{ | |
CallPointerMethod("DllUnregisterServer"); | |
} | |
private void CallPointerMethod(string methodName) | |
{ | |
IntPtr dllEntryPoint = GetProcAddress(hLib, methodName); | |
if (IntPtr.Zero == dllEntryPoint) | |
{ | |
throw new Win32Exception(Marshal.GetLastWin32Error()); | |
} | |
PointerToMethodInvoker drs = | |
(PointerToMethodInvoker) Marshal.GetDelegateForFunctionPointer(dllEntryPoint, | |
typeof(PointerToMethodInvoker)); | |
drs(); | |
} | |
public void Dispose() | |
{ | |
if (IntPtr.Zero != hLib) | |
{ | |
UnRegisterComDLL(); | |
FreeLibrary(hLib); | |
hLib = IntPtr.Zero; | |
} | |
} | |
} | |
// | |
// How to Use | |
// | |
using (Registrar registrar = new Registrar("path\\to\\com.dll")) | |
{ | |
registrar.RegisterComDLL(); | |
return base.Execute(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment