Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoCreateInstance exact match in .NET?

I have in-proc (DLL) COM Server, but I settled in to run as DllSurrogate, for this reason from unmanaged code (Delphi) i have:

function TComWrapper.GetServer: IUnknown;
begin
  OleCheck(CoCreateInstance(ServerData^.ClassId, nil, CLSCTX_LOCAL_SERVER, IUnknown, Result));
end;

from C# am using now:

[DllImport("ole32.dll", EntryPoint = "CoCreateInstance", CallingConvention = CallingConvention.StdCall)]
static extern UInt32 CoCreateInstance([In, MarshalAs(UnmanagedType.LPStruct)] Guid rclsid,
   IntPtr pUnkOuter, UInt32 dwClsContext, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
   [MarshalAs(UnmanagedType.IUnknown)] out object rReturnedComObject);

...

            UInt32 dwRes = CoCreateInstance(ClassIdGuid,
                                            IntPtr.Zero,
                                            (uint)(CLSCTX.CLSCTX_LOCAL_SERVER), //if OR with CLSCTX_INPROC_SERVER then INPROC Server will be created, because of DLL COM Server
                                            IUnknownGuid,
                                            out instance);

Above code is unsafe. Does it exists safe version fro above CoCreateInstance? It seems that Activator.CreateInstance doesn't help me. I have to set explicitly running Context (3rd parameter)

like image 350
ALZ Avatar asked Feb 16 '23 20:02

ALZ


1 Answers

You could also do this:

[ComImport]
[Guid(YourGuidGoesHere)]
private class MyClass
{
}

and create an instance of the COM Object like this:

  IYourInterface myClass = (IYourInterface)(new MyClass());

Without using p/invoke.

like image 96
Simon Mourier Avatar answered Feb 28 '23 13:02

Simon Mourier