How can I wrap a COM object in a native .NET class?

后端 未结 4 1027
醉梦人生
醉梦人生 2021-02-05 10:53

I\'m using an extensive existing COM API (could be Outlook, but it\'s not) in .NET (C#). I\'ve done this by adding a \"COM Reference\" in Visual Studio so all the \"magic\" is

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-05 11:21

    You, yourself aren't dealing with COM objects. You are already dealing with a facade that was created the moment you added a reference to the COM binary to your project. (.NET) will generate a facade for you, therefore simplifying the task of using COM objects to simply using regular .NET classes. If you do not like the interface that's generated for you, you should probably create a facade to the existing facade. You don't have to worry about COM intricacies, because that's already been done for you (there may be some things you do need to worry about, but I think they are few and far between). Just use the class as a regular .net class because that's exactly what it is, and deal with any problems as they arise.

    EDIT: One of the problems you might experience is nondeterministic COM object destruction. The reference counting that's taking place behind the scenes relies on garbage collection so you can't be sure when your objects will be destroyed. Depending on your application you may need more deterministic destruction of your COM objects. To do this you would use Marshal.ReleaseComObject. If this is the case, then you should be aware of this gotcha.

    Sorry, I would post more links, but apparently I can't post more than 1 without first getting 10 reputation.

提交回复
热议问题