如何在Delphi 中調用C#生成的DLL類庫

最近需要寫一個和給上位機和下位機通訊的接口,而上位機是用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)]//此句必須存在,否則Delphi導入時,類中無方法
    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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章