我有进程(DLL)COM服务器,但我决定以DllSurrogate运行,因此我从非托管代码(Delphi):
function TComWrapper.GetServer: IUnknown;
begin
OleCheck(CoCreateInstance(ServerData^.ClassId, nil, CLSCTX_LOCAL_SERVER, IUnknown, Result));
end;
来自C#am现在使用:
[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
对我没有帮助。我必须设置显式运行Context(第三个参数)
答案 0 :(得分:6)
你也可以这样做:
[ComImport]
[Guid(YourGuidGoesHere)]
private class MyClass
{
}
并创建一个COM对象的实例,如下所示:
IYourInterface myClass = (IYourInterface)(new MyClass());
不使用p / invoke。