以前用delphi寫的CS程式 今天客戶要加幾個模組上去 ,剛好會點C# ,這後面模組就用C#寫的編譯成dll檔案, 在用delphi調用C#寫的dll檔案時折騰好陣子 就有了這些經曆寫下來。
一、開啟vs2005
建立windows應用程式項目命名為SFrm,刪除應用程式自動產生的Program.cs
(因為我們是要產生dll檔案)
在表單類建立一介面(interface SHFRM) 讓表單類實現介面 代碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace SFrm
{
public interface SHFRM //此介面用在delphi下調用必須用到
{
void ShchildFrm();
}
public partial class Form1 : Form,SHFRM
{
private BindingSource bindingSource1 = new BindingSource();
private SqlDataAdapter dataAdapter = new SqlDataAdapter();
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 顯示視窗
/// </summary>
public void ShchildFrm()
{
Form1 frm = new Form1();
frm.Show();
}
/// <summary>
/// 按鈕事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = bindingSource1;
GetData("select * from Customers");
}
private void GetData(string selectCommand)
{
try
{
String connectionString = "Data Source=.;initial catalog=Northwind;user id =sa;pwd=";
dataAdapter = new SqlDataAdapter(selectCommand, connectionString);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
catch (SqlException)
{
MessageBox.Show("To run this example, replace the value of the " +
"connectionString variable with a connection string that is " +
"valid for your system.");
}
}
}
}
右擊項目名在屬性對話方塊中更改輸出類型為”類庫” 在介面點擊程式集資訊 按鈕 如:
使程式集com可見必須選中
完成dll檔案產生
二.DotNet 類庫打包成COM類型庫(在vs命令列執行如下操作)
Tlbexp.exe SFrm.dll /out: SFrm.tlb
三.註冊COM類型庫
Regasm.exe SFrm.dll
四.Delphi匯入類型庫
Delpi 中, Project -> Import Type Library ,選中類型庫:dotnet2com.tlb,
產生 DotNet2Com_TLB 單元檔案。單元檔案中有介面 SHFRM。
SHFRM = interface(IDispatch)
['{D8400C54-E4B2-36BD-B970-45CD204F319A}']
procedure ShchildFrm; safecall;
end;和代理類聲明 TForm1及獲得 SHFRM 介面的屬性:
property DefaultInterface: _Form1 read GetDefaultInterface;
五.Delphi 中使用
uses
SFrm_TLB;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
Frm:TForm1;
begin
Frm:=TForm1.Create(self);
(Frm.DefaultInterface as SHFRM).ShchildFrm();//顯示dll檔案裡表單
end;
delhi程式運行結果如:
註:在程式運行環境必須安裝。net環境並註冊dll檔案 否則會報:無註冊類別