Skip to content

Instantly share code, notes, and snippets.

@haroldcris
Last active March 25, 2017 09:54
Show Gist options
  • Save haroldcris/c743a3d38613c73ce874ff650d6d6584 to your computer and use it in GitHub Desktop.
Save haroldcris/c743a3d38613c73ce874ff650d6d6584 to your computer and use it in GitHub Desktop.
Register DLL from C#
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