CoCreateInstance exact match in .NET?

天大地大妈咪最大 提交于 2019-12-22 09:39:32

问题


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:


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.



来源:https://stackoverflow.com/questions/15987491/cocreateinstance-exact-match-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!