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 make unreg all the dlls of the first version and reg all the dlls 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 takes a long time :) (for each dll will start as many as 2 processes, on reg and on anreg) ...
    Therefore, the following code was written. He is not of great value, but because a search in google about the implementation of registering a com server on .NET did not give anything similar, then 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);
    }

    Also popular now: