在 C#/.Net 中创建进程外 COM?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/446417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:41:32  来源:igfitidea点击:

Create Out-Of-Process COM in C#/.Net?

c#com

提问by Huck

I need to create an out-of-process COM server (.exe) in C# that will be accessed by multiple other processes on the same box. The component has to be a single process because it will cache the information it provides to its consumers in memory.

我需要在 C# 中创建一个进程外 COM 服务器 (.exe),它将被同一台机器上的多个其他进程访问。该组件必须是单个进程,因为它将在内存中缓存它提供给消费者的信息。

Note: the processes that will access my COM Server are mostly Matlab processes, thus the necessityfor a COM interface.

注意:访问我的 COM 服务器的进程大多是 Matlab 进程,因此需要一个 COM 接口。

I have seen threads regarding creating in-process COM components in .Net on stack overflow (Create COM ...) and on the web, but am having a hard time to find a way to create out-of-process components with .Net.

我已经看到有关在堆栈溢出(Create COM ...)和网络上在 .Net 中创建进程内 COM 组件的线程,但是我很难找到一种使用 .Net 创建进程外组件的方法.

How is this achievable? Any suggested references?

这是如何实现的?有什么推荐的参考吗?

Thanks.

谢谢。

采纳答案by Marc Gravell

One option is serviced components- i.e. host it in COM+ as the shell exe. See also the howto here.

一种选择是服务组件- 即在 COM+ 中将其作为 shell exe 托管。另请参阅此处的操作方法

回答by Aamir

IMO, one of the ways through which this can be done is to create a normal COM Dll as per the method you mentioned in the link and then after registering your COM dll, change it to a surrogate DLL. This can be done very easily through OLEView utility, although you can do it manually as well by changing registry entries as well through the method mentioned at http://msdn.microsoft.com/en-us/library/ms686606(VS.85).aspx.

IMO,其中一种方法是根据您在链接中提到的方法创建一个普通的 COM Dll,然后在注册您的 COM dll 后,将其更改为代理 DLL。这可以通过 OLEView 实用程序轻松完成,尽管您也可以通过更改注册表项以及通过http://msdn.microsoft.com/en-us/library/ms686606(VS.85) 中提到的方法手动完成).aspx

By making this a surrogate DLL, it will run in it's own dllhost.exe and hence will be out-of-process.

通过将其设为代理 DLL,它将在其自己的 dllhost.exe 中运行,因此将处于进程外。

回答by Rhys

We too had some issues many years ago with regasm and running the COM class as a Local EXE Server.

多年前,我们在 regasm 和将 COM 类作为本地 EXE 服务器运行时也遇到了一些问题。

This is a bit of a hack and I'd welcome any suggestions to make it more elegant. It was implemented for a project back in the .NET 1.0 days and has not been touched since then!

这是一个小技巧,我欢迎任何建议以使其更优雅。它是在 .NET 1.0 时代为一个项目实现的,从那时起就没有被触及!

Basically it performs a regasm style of registration each time the application starts (it needs to be run once to make registry entries before the COM object is instantiated in the COM container application).

基本上,每次应用程序启动时,它都会执行 regasm 样式的注册(在 COM 容器应用程序中实例化 COM 对象之前,它需要运行一次以创建注册表项)。

I've copied the following important bits from our implementation and renamed a few classes to illustrate the example.

我从我们的实现中复制了以下重要部分,并重命名了一些类来说明示例。

The following method is called from the Form Loaded event to register the COM class(renamed to MyCOMClassfor this example)

从 Form Loaded 事件调用以下方法来注册 COM 类(MyCOMClass在本例中重命名为)

private void InitialiseCOM()
    {
        System.Runtime.InteropServices.RegistrationServices services = new System.Runtime.InteropServices.RegistrationServices();
        try
        {
            System.Reflection.Assembly ass = Assembly.GetExecutingAssembly();
            services.RegisterAssembly(ass, System.Runtime.InteropServices.AssemblyRegistrationFlags.SetCodeBase);
            Type t = typeof(MyCOMClass);
            try
            {
                Registry.ClassesRoot.DeleteSubKeyTree("CLSID\{" + t.GUID.ToString() + "}\InprocServer32");
            }
            catch(Exception E)
            {
                Log.WriteLine(E.Message);
            }

            System.Guid GUID = t.GUID;
            services.RegisterTypeForComClients(t, ref GUID );
        }
        catch ( Exception e )
        {
            throw new Exception( "Failed to initialise COM Server", e );
        }
    }

For the type in question, MyCOMObject, will need some special attributes to be COM compatible. One important attribute is to specify a fixed GUID otherwise each time you compile the registry will fill up with orphaned COM GUIDs. You can use the Tools menu in VisualStudio to create you a unique GUID.

对于有问题的类型,MyCOMObject, 将需要一些特殊属性才能与 COM 兼容。一个重要的属性是指定一个固定的 GUID,否则每次编译注册表时都会填满孤立的 COM GUID。您可以使用 VisualStudio 中的“工具”菜单来创建唯一的 GUID。

  [GuidAttribute("D26278EA-A7D0-4580-A48F-353D1E455E50"),
  ProgIdAttribute("My PROGID"),
  ComVisible(true),
  Serializable]
  public class MyCOMClass : IAlreadyRegisteredCOMInterface
  {
    public void MyMethod()
    {
    }

    [ComRegisterFunction]
    public static void RegisterFunction(Type t)
    {
      AttributeCollection attributes = TypeDescriptor.GetAttributes(t);
      ProgIdAttribute ProgIdAttr = attributes[typeof(ProgIdAttribute)] as ProgIdAttribute;

      string ProgId = ProgIdAttr != null ? ProgIdAttr.Value : t.FullName;

      GuidAttribute GUIDAttr = attributes[typeof(GuidAttribute)] as GuidAttribute;
      string GUID = "{" + GUIDAttr.Value + "}";

      RegistryKey localServer32 = Registry.ClassesRoot.CreateSubKey(String.Format("CLSID\{0}\LocalServer32", GUID));
      localServer32.SetValue(null, t.Module.FullyQualifiedName);

      RegistryKey CLSIDProgID = Registry.ClassesRoot.CreateSubKey(String.Format("CLSID\{0}\ProgId", GUID));
      CLSIDProgID.SetValue(null, ProgId);

      RegistryKey ProgIDCLSID = Registry.ClassesRoot.CreateSubKey(String.Format("CLSID\{0}", ProgId));
      ProgIDCLSID.SetValue(null, GUID);

      //Registry.ClassesRoot.CreateSubKey(String.Format("CLSID\{0}\Implemented Categories\{{63D5F432-CFE4-11D1-B2C8-0060083BA1FB}}", GUID));
      //Registry.ClassesRoot.CreateSubKey(String.Format("CLSID\{0}\Implemented Categories\{{63D5F430-CFE4-11d1-B2C8-0060083BA1FB}}", GUID));
      //Registry.ClassesRoot.CreateSubKey(String.Format("CLSID\{0}\Implemented Categories\{{62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}}", GUID));
    }

    [ComUnregisterFunction]
    public static void UnregisterFunction(Type t)
    {
      AttributeCollection attributes = TypeDescriptor.GetAttributes(t);
      ProgIdAttribute ProgIdAttr = attributes[typeof(ProgIdAttribute)] as ProgIdAttribute;

      string ProgId = ProgIdAttr != null ? ProgIdAttr.Value : t.FullName;

      Registry.ClassesRoot.DeleteSubKeyTree("CLSID\{" + t.GUID + "}");
      Registry.ClassesRoot.DeleteSubKeyTree("CLSID\" + ProgId);
    }

  }

The InitialiseCOMmethod in the main form uses RegistrationServicesto register the type. The framework then uses reflection to find the method marked with the ComRegisterFunctionattribute and calls that function with the type being registered.

InitialiseCOM主窗体中的方法RegistrationServices用于注册类型。然后,框架使用反射来查找标记有该ComRegisterFunction属性的方法,并使用正在注册的类型调用该函数。

The ComRegisterFunctionmarked method, hand creates the registry settings for a Local EXE Server COM object and this can be compared with regasm if you use REGEDITand find the keys in question.

ComRegisterFunction标记方法,一方面创造了一个本地EXE服务器的COM对象的注册表设置,这可以与regasm如果使用进行对比REGEDIT,发现有问题的钥匙。

I've commented out the three \\Registry.ClassesRoot.CreateSubKeymethod calls as this was another reason we needed to register the type ourselves as this was an OPC server and third party OPC clients use these implemented categories to scan for compatible OPC servers. REGASM would not add these in for us unless we did the work ourselves.

我已经注释掉了三个\\Registry.ClassesRoot.CreateSubKey方法调用,因为这是我们需要自己注册类型的另一个原因,因为这是一个 OPC 服务器,第三方 OPC 客户端使用这些实现的类别来扫描兼容的 OPC 服务器。除非我们自己完成工作,否则 REGASM 不会为我们添加这些。

You can easily see how this works if you put break points on the functions as it is starting.

如果在函数开始时在函数上放置断点,您可以很容易地看到它是如何工作的。

Our implementation used an interface that was already registered with COM. For your application you will either need to :-

我们的实现使用了一个已经向 COM 注册的接口。对于您的申请,您要么需要:-

  1. Extend the registration methods listed above to register the interface with COM
  2. Or create a separate DLL with the interface definition and then export that interface definition to a type library and register that as discussed in the StackOverflow link you added in the question.
  1. 扩展上面列出的注册方法,用COM注册接口
  2. 或者使用接口定义创建一个单独的 DLL,然后将该接口定义导出到类型库并注册,如您在问题中添加的 StackOverflow 链接中所述。

回答by Rhys

You can use RegistrationServices.RegisterTypeForComClients, which is the managed equivalent of CoRegisterClassObject - for sample code see here.

您可以使用 RegistrationServices.RegisterTypeForComClients,它是 CoRegisterClassObject 的托管等效项 - 有关示例代码,请参见此处

回答by Sasha Grn

It could be done using umanaged ATL framework and plumbing it with the managed code (simple by changing the result project properties to /clr).

它可以使用 umanaged ATL 框架完成,并将其与托管代码连接起来(通过将结果项目属性更改为 /clr 很简单)。

Here are illustrative snippets:

以下是说明性片段:

.H-part:

\#include < vcclr.h >

\#using < MyCSharpModule.dll >

using namespace System;

class ATL_NO_VTABLE MyCSharpProxyServer :
    public CComObjectRootEx< CComMultiThreadModel >,

.....

{

      HRESULT FinalConstruct();

      STDMETHODIMP LoadMyFile(BSTR FileName);
.....
      gcroot<MyCSNamespace::MyCSharpClass^> m_CSClass;

}

.CPP-part:

using namespace System::Collections;

using namespace MyCSNamespace;

HRESULT MyCSharpProxyServer::FinalConstruct()
{

    m_CSClass = gcnew MyCSharpClass();

}

STDMETHODIMP MyCSharpProxyServer::LoadMyFile(BSTR FileName)
{

    try {
       int hr = m_CSClass->LoadFile(gcnew String( FileName));
        return hr;
    }
    catch( Exception^ e )  {
        return E_FAIL;
    }
}

The C# part (MyCSharpClass class) lives in a separate project with output type Class Library.

C# 部分(MyCSharpClass 类)位于具有输出类型类库的单独项目中。

回答by Marius Bancila

Use the flag REGCLS_MULTIPLEUSEwith CoRegisterClassObject() to make the coclass a multiuse class. Here is more info: http://support.microsoft.com/kb/169321.

使用标志REGCLS_MULTIPLEUSE和 CoRegisterClassObject() 使 coclass 成为多用途类。这是更多信息:http: //support.microsoft.com/kb/169321

回答by Malick

The visual studio project "CSExeCOMServer" that you can find here(All-in-One), gives a full example.

您可以在此处(All-in-One)找到的 Visual Studio 项目“CSExeCOMServer”给出了一个完整示例。

回答by Abraham

ActiveX.NET, is a true Out-Of-Proc (EXE) COM Server implementation in C#.NET. This one has a cleaner implementation compared to the original CSExeCOMServer, published in Code.MSDN.

ActiveX.NET是 C#.NET 中真正的过程外 (EXE) COM 服务器实现。与Code.MSDN中发布的原始CSExeCOMServer相比,这个实现更清晰。

ActiveX.NEThas features like it does use a .NET Message Pump (instead of native) and uses MEF Plugin model, so that the EXE Server is decoupled and can be shared among multiple COM Plugins, which can be developed independently

ActiveX.NET具有使用.NET消息泵(而不是原生)和MEF Plugin模型的特点,因此EXE Server是解耦的,可以在多个COM Plugins之间共享,可以独立开发