从 C# 访问 COM 对象的最佳方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/635839/
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 11:11:35  来源:igfitidea点击:

Best way to access COM objects from C#

c#.netcompinvoke

提问by Tony the Pony

I am planning to use various objects that are exposed as COM objects. To make them easier to use, I'd like to wrap them as C# objects. What is the best approach for this?

我计划使用作为 COM 对象公开的各种对象。为了使它们更易于使用,我想将它们包装为 C# 对象。最好的方法是什么?

采纳答案by Robert P

If the library is already registered, you can perform the following steps to have Visual Studio generate an interop assembly for you:

如果库已注册,您可以执行以下步骤让 Visual Studio 为您生成互操作程序集:

  • Open to your Visual Studio project.
  • Right click on 'References' (right under the project in your Solution Explorer) and select 'Add Reference'.
  • Select the COM tab. (If you don't see this, you have a project type that doesn't support COM.)
  • Select the Component you wish to interop with.
  • Select 'ok'.
  • 打开您的 Visual Studio 项目。
  • 右键单击“引用”(就在解决方案资源管理器中的项目下方)并选择“添加引用”。
  • 选择 COM 选项卡。(如果你没有看到这个,你的项目类型不支持 COM。)
  • 选择要与之互操作的组件。
  • 选择“确定”。

This will be a class or set of C# classes that wrap all of the COM interface stuff with a normal C# class. Then you just use it like any other C# library. If the import of the reference worked well, you can explore it like any other reference and the methods/structs/classes/constants should show up in that namespace and intellisense.

这将是一个类或一组 C# 类,用一个普通的 C# 类包装所有的 COM 接口内容。然后您就可以像使用任何其他 C# 库一样使用它。如果引用的导入运行良好,您可以像任何其他引用一样探索它,并且方法/结构/类/常量应该显示在该命名空间和智能感知中。

This will get you started, at least. If this is deployed in a corporate environment or one you can control, this may be all you need.

这至少会让你开始。如果这部署在公司环境中或您可以控制的环境中,这可能就是您所需要的。

回答by Steve

You can (initially) just import the reference. If you need more control (or get errors from VS's import) you can use tlbimp in the windows sdk. This will create the interop assemblies. You can get class definitions from metadata.

您可以(最初)只导入引用。如果您需要更多控制(或从 VS 的导入中获取错误),您可以在 windows sdk 中使用 tlbimp。这将创建互操作程序集。您可以从元数据中获取类定义。

EDIT: This is actually a lot more complicated if you want to work with 64 bit

编辑:如果您想使用 64 位,这实际上要复杂得多

回答by user69889

There is a good article from MSDN on this, that explains the managed and unmanaged code, and walks you step by step how to do it. http://msdn.microsoft.com/en-us/library/ms973800.aspx#

MSDN 上有一篇很好的文章,它解释了托管和非托管代码,并逐步指导您如何操作。 http://msdn.microsoft.com/en-us/library/ms973800.aspx#

Have fun!

玩得开心!