Delphi调用C#类库 - chenghm2003 - 博客园

来源:百度文库 编辑:神马文学网 时间:2024/04/28 04:51:13
以前用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 BindingSourcebindingSource1 = new BindingSource();
private SqlDataAdapter dataAdapter =new SqlDataAdapter();
public Form1()
{
InitializeComponent();
}
///
/// 显示窗口
///

public void ShchildFrm()
{
Form1 frm = new Form1();
frm.Show();
}
///
/// 按钮事件
///

///
///
private void button1_Click(objectsender, EventArgs e)
{
dataGridView1.DataSource =bindingSource1;
GetData("select * fromCustomers");
}
private void GetData(stringselectCommand)
{
try
{
String connectionString ="Data Source=.;initial catalog=Northwind;user id =sa;pwd=";
dataAdapter = newSqlDataAdapter(selectCommand, connectionString);
SqlCommandBuildercommandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = newDataTable();
table.Locale =System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource =table;
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
catch (SqlException)
{
MessageBox.Show("To runthis example, replace the value of the " +
"connectionStringvariable with a connection string that is " +
"valid for yoursystem.");
}
}
}
}
右击项目名在属性对话框中更改输出类型为”类库” 在界面点击程序集信息 按钮 如下图:
使程序集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: _Form1read GetDefaultInterface;
五.Delphi 中使用
uses
SFrm_TLB;
{$R *.dfm}
procedure TForm1.Button1Click(Sender:TObject);
var
Frm:TForm1;
begin
Frm:=TForm1.Create(self);
(Frm.DefaultInterface asSHFRM).ShchildFrm();//显示dll文件里窗体
end;
delhi程序运行结果如下图:
注:在程序运行环境必须安装。net环境并注册dll文件 否则会报:无注册类别