Best way to access COM objects from C#

a 夏天 提交于 2019-12-17 03:08:49

问题


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?


回答1:


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

  • 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'.

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.

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.




回答2:


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#

Have fun!




回答3:


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.

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



来源:https://stackoverflow.com/questions/635839/best-way-to-access-com-objects-from-c-sharp

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