日期:2014-05-18  浏览次数:20957 次

C#调用COM组件的几个步骤
C#调用COM组件首先要将信息进行转化,并进行测试。希望本文能对大家了解C#调用COM组件有所帮助。

AD:


这里我们将介绍C#调用COM组件的几个步骤,先将Com类型信息转换为.NET元数据,然后查看元数据,最后测试程序。

首先将Com类型信息转换为.NET元数据

tlbimp sample.dll /out: sample_clw.dll 工具:Tlbimp.exe(类型库导入程序 )
示例:tlbimp  d:\before\TKSnsOCom.dll   /out:d:\convertered\TKWSns
OCom.dll
(以管理员身份运行visual studio命令行工具)

参考:.Net framework SDK 文档

ms-help://MS.NETFrameworkSDK.CHS/cptools/html/cpgrftypelibraryimportertlbimpexe.htm 查看元数据

工具:ILDasm

参考:ms-help://MS.NETFrameworkSDK.CHS/cptutorials/html/il_dasm_tutorial.htm

测试程序:

生成一个console programme

在project->add reference里,选择com,browser你的com,select

ok,现在在你的bin目录下应该有一个sample_clw.dll了

下面我们来用sample_clw的方法

using System; 
using sample_clw; 
namespace CompConsole 

/// <summary> 
/// Class1 的摘要说明。
/// </summary> 
class Class1 

/// <summary>
/// 应用程序的主入口点。 
/// Date:2003/6/20 
/// </summary> 
[STAThread] 
static void Main(string[] args) 
{  //  // TODO: 在此处添加代码以启动应用程序 
Console.Write ("=======Demo for Call com functions in c#=============\n");  
sampleClass sam = new sampleClass();
//now we call functions 
  sam.SayHello();
  }
}

错误:无法实例化类
解决方法:右键dll熟悉,将嵌入互操作类型改为false.