最近需要寫一個和給上位機和下位機通訊的接口,而上位機是用Delphi開發的,所以就需要用C#做一類庫給Delphi調用
大概步驟:
1、首先在VS2008中新建一個類項目名為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; begin obj :=CoTest.Create; //創建實例,默認會在C#的類前面加Co td := 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\microsoft.net\v2.0 下面
regasm /tlb:dllName.tlb dllName.dll