最近需要写一个和给上位机和下位机通讯的接口,而上位机是用Delphi开发的,所以就需要用C#做一类库给Delphi调用
大概步骤:
1、首先在VS中新建一个类项目名为TestDelphi,然后添加一个接口文件命名为ITest.cs
源代码如下:
using System;using System.Collections.Generic;using System.Text;using System.Runtime.InteropServices;namespace TestDelphi{public interface ITest{int add(int x, int y);string getSysName();byte ArrAdd(byte x, byte y);DateTime GetTime(DateTime dt);}}
再建一个实现类文件 Test.cs
using System;using System.Collections.Generic;using System.Text;using System.Runtime.InteropServices;namespace TestDelphi{[ClassInterface(ClassInterfaceType.None)]public class Test:ITest{public Test(){ }public int add(int x, int y){return x + y;}public DateTime GetTime(DateTime dt){return dt.AddDays(2);}public string getSysName(){return "I don't care";}public byte ArrAdd(byte x, byte y){byte[] arr = new byte[2];arr[0] = x;arr[1] = y;return arr[0];}}}
然后在项目属性的程序集设置使Com可见,在生成那里勾选“为Com互操作注册”.
然后在生成时间中的“生成后事件命令行”中输入
"C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\tlbexp" "$(TargetPath)"
该命令是为了在生成的时候同时产生一个.TLB文件,在Delphi中添加库中时需要用到。
2、打开delphi 7 然后在project菜单选择import type library——>Add 选择生成的TestDelphi.TLB
然后Palatte Page 选择Com+
然后单击Create Unit按钮将会生成unit TestDelphi_TLB
完成以上操作之后就可以在窗体上的Unit中引用TestDelphi_TLB
在窗体上添加一个按钮,在按钮的事件中这样写
procedure TForm1.Button2Click(Sender: TObject);var obj:ITest; //定义在C#中的接口变量arr : byte;td:TDateTime;beginobj :=CoTest.Create; //创建实例,默认会在C#的类前面加Cotd := now; //获取当前时间td := obj.GetTime(td); //调用接口的方法showmessage(datetimetostr(td)); // 返回的结果是当前时间+2天arr :=obj.ArrAdd(12,13); //返回的是第一个参数showmessage(inttostr(obj.add(1,2))); //返回的是1+2的结果showmessage(obj.getSysName()); //返回字符串end;
此为在Delphi中调用C#的类库的方法
注:在调用过程中可能出现Project xxxx raised exception class EOleSysError with message '系统找不到指定文件'.
开始在网上找了半天没找到什么原因,后来想了下应该是要把dll文件放在delphi的projects目录下,运行的时候需要dll,后来问题成功解决。
在只有.NET 2.0环境下的机器上,需要使用regasm注册
一般目录在 c:\windows\\v2.0 下面
regasm /tlb:dllName.tlb dllName.dll