问题描述
好吧,我创建了一个c#dll,使其所有的接口和方法都是ComVisible(true)。使用gacutil将它添加到GAC,然后使用regasm注册它并创建一个类型库tlb文件。
现在我有另一个c#项目,我想调用com对象,我该怎么做呢?
第1步:创建一个
有两种方法
方法1:使用TlbImp生成RCW
tlbimp< YourCOMSvr> .tlb /out:<YourCOMSvr>.dll
使用这种方式使用默认的.NET-Interop Marshalling,有时(意味着当它不工作时)您需要通过执行附加步骤来更改编组
ildasm< YourCOMSvr> .dll /out:<YourCOMSvr> ;.il
//修改< YourCOMSvr> .il
方法2:手动创建一个C ++ / Cli项目作为一个用于创建C ++ / Cli项目的工具。 COM服务器的包装器
步骤2:C#代码
RCW并使用以下代码连接到COM服务器
键入yourComType = Type.GetTypeFromProgID(yourComSvrProgID,serverPcName);
var oInterface =(IYourCOMInterface)Activator.CreateInstance(yourComType);
//然后开始使用oInterface
Ok, I've created a c# dll, made all its interface and methods all ComVisible(true). Added it to the GAC using gacutil, then registered it using regasm and created a type library tlb file.
Now I have another c# project that I want to make calls to that com object, how can I do this? What would the code roughly look like to import the com object then use its calls?
解决方案 Step 1: Create a Runtime-Callable-Wrapper.There are two ways
Method 1: using TlbImp to Generate RCW
tlbimp <YourCOMSvr>.tlb /out:<YourCOMSvr>.dll
using this way is using the default .NET-Interop Marshalling, sometimes (Meaning when it does not work) you need to change the marshalling by perform the additional steps
ildasm <YourCOMSvr>.dll /out:<YourCOMSvr>.il
//Modify <YourCOMSvr>.il
ilasm <YourCOMSvr>.il /dll
Method 2: Manually create a C++/Cli project serves as a wrapper for the COM server
Step 2: C# Code
Reference the RCW and use the following code to connect to the COM Server
Type yourComType= Type.GetTypeFromProgID(yourComSvrProgID, serverPcName);
var oInterface = (IYourCOMInterface)Activator.CreateInstance(yourComType);
//Then start using oInterface
这篇关于调用C#COM对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!