📜 ⬆️ ⬇️

regsrv32.exe on .NET / Register COM server from .NET

The problem was this:
The client had to switch between two versions of the application, which uses about 1000 com objects.
To switch, you need to unreg all dll of the first version and reg all dll of the second version ... Then, when you need to switch to the first version again, repeat the process in the opposite direction ...
You can run regsrv32.exe many times, however, it is long and hard :) (for each dll, as many as 2 processes will be running, reg and anreg) ...
Therefore, the following code was written. Of great value, he is not, but because google search for the implementation of the registration of the com server on .NET did not give anything like that, I bring it here for indexing and use by those who suddenly need :)

// regsrv32 .NET . register com server via .net
private void RegDll(string mDll) {
IntPtr pDll = NativeMethods.LoadLibrary(@"path_to_dll\your.dll");
if (pDll == IntPtr.Zero) {
//......
}

IntPtr pDllRegServ = NativeMethods.GetProcAddress(pDll, "DllRegisterServer");
IntPtr pDllUnRegServ = NativeMethods.GetProcAddress(pDll, "DllUnregisterServer");
// check ptrs for zero...

DllFuncServer reg =
(DllFuncServer) Marshal.GetDelegateForFunctionPointer(pDllRegServ, typeof(DllFuncServer));

DllFuncServer unReg =
(DllFuncServer)Marshal.GetDelegateForFunctionPointer(pDllUnRegServ, typeof(DllFuncServer));

int resUnreg = unReg();
int resReg = reg();
bool result = NativeMethods.FreeLibrary(pDll);
Console.Write(resUnreg + " " + resReg);
}

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int DllFuncServer();

static class NativeMethods {
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);

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

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

')

Source: https://habr.com/ru/post/62118/


All Articles