CoCreateInstance在.net中的精确匹配

本文关键字:net CoCreateInstance | 更新日期: 2023-09-27 18:09:03

我有进程内(DLL) COM服务器,但我定居在运行作为dllproxy,出于这个原因,从非托管代码(Delphi)我有:

function TComWrapper.GetServer: IUnknown;
begin
  OleCheck(CoCreateInstance(ServerData^.ClassId, nil, CLSCTX_LOCAL_SERVER, IUnknown, Result));
end;
[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);
上面的代码是不安全的。是否存在CoCreateInstance以上的安全版本?看来Activator.CreateInstance对我没有帮助。我必须明确设置运行上下文(第三个参数)

CoCreateInstance在.net中的精确匹配

你也可以这样做:

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

并创建一个COM对象的实例,像这样:

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