CoCreateInstance exact match in .NET?

2019-05-15 02:33发布

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)

1条回答
放荡不羁爱自由
2楼-- · 2019-05-15 03:16

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.

查看更多
登录 后发表回答