Delphi 調用C# 編寫的DLL方法

近來,因工做須要,必須解決Delphi寫的主程序調用C#寫的dll的問題。在網上一番搜索,又通過種種試驗,最終證實有如下兩種方法可行:
    編寫C#dll的方法都同樣,首先在vs2005中建立一個「類庫」項目TestDll,
using System.Runtime.InteropServices;
namespace TestDll
{
     public   interface  I TestClass
    {
       void YourProcedure(stirng param1);
    }
   [ClassInterface(ClassInterfaceType.None)]
    public   class TestClass:I TestClass
    {
       public void YourProcedure (stirng param1);
       {    //本身的代碼    }
    }  
}
完成以後,設置項目的屬性「Make assembly COM-Visible」爲選中狀態。編譯以後獲得 TestClass.dll,把此dll放到Delphi主程序目錄下。打開vs2005自帶的工具「Visual Studio 2005命令提示」,輸入
Regasm  路徑/TestClass.dll 向系統註冊此dll。

Delphi程序調用此Dll方式有兩種:
1、打開vs2005自帶的工具「Visual Studio 2005命令提示」,輸入 TlbExp  路徑/TestClass.dll 獲得一個TestClass.tlb 文件。打開Delphi,選擇「Project」--「import type library」找到剛纔的TestClass.tlb,點擊 CreateUnit,向delphi中引入一個com接口。
delphi 調用代碼以下:
  var aClass: TestClass;
  begin
    aClass : =  CoTestClass.Create;
    aClass. YourProcedure ('參數');
  end;
2、不需生成tlb文件,仿照調用Excel的方式。代碼以下:
 var aClass: Variant;
begin
  aClass:= CreateOleObject('TestDll.TestClass');
  aClass.YourProcedure ('參數');
end;

以上兩種方法均可以調用成功,其中調用regasm.exe向系統註冊dll是必需的。第一種方法須要生成tlb文件,並引入delphi中,操做繁瑣,但能夠看到接口的定義。第二種方法操做簡單,但看不到接口的定義。
工具

轉:http://blog.csdn.net/genispan/article/details/4294487spa

相關文章
相關標籤/搜索