Delphi拥有强大的控件群, 如何使用这些控件一 直苦恼着我们这些C++Builder 的追随者, 我通过一些项目的实践掌握了一些如何在C++Builder中使用Delphi控件的方法。
我 的 使C++Builder 使 用Delphi VCL 类 库 的 方 法 基 于Windows 中 较 通 用 的DLL 方 式。 在 实 际 应 用 中 找 到 了 将VCL 控 件 转 化为DLL 库, 在C++Builder 动 态 调 用DLL。 此 法 适 用 于 非 可 视VCL 控件。
假 令 在Delphi 中 有 一Sample 控 件, 有 属 性 Actived、Pro1、Pro2,欲 将 这 个 控 件 转 到C++Builder 中 使 用。
一:Delphi 中DLL 的 制 作
1.在Delphi 中 新 建 一DLL 项 目SampleDLL , 时 在此 项
目 中Create 一 个 新 的 类TTtempcomp 基 类 为TComponent 即 也 为一 个 控 件, 在
其 中 加 入 一 个constructor Create1, 但 不 作 任 何动 作;
2.在 DLL 中 加 入 要 导 出 的 属 性 的Function(Actived、Pro1、Pro2)&Create、Destroy
的 框 架, Exports 中 加 入 导 出 的Function、Procdure 名 称;
3.在DLL 的 主 过 程 中 对TTempcomp 的 实 例temp1 进 行Create1,
另 外 保 存 出 口 和 设 置ExitProc;
4.在OpenSample 的 函 数 中 加 入 HwCtrl:= Sample1.Create(temp1)
对Sample 进 行 实 例 化, 对 CloseSample 和 其 它 属 性 加 入 相 应 的语 句;
二:C++Builder 中DLL 的 使 用
1.将Delphi 中 生 成 的DLL 用implib 生 成LIB 文 件加 入
C++Builder 的 工 程 文 件;
2.在 头 文 件 中 加 入 extern "C" __declspec(dllimport)
bool _stdcall
OpenSa e(void);
extern "C" __declspec(dllimport) void _stdcall
CloseSample(void);
extern "C" __declspec(dllimport) bool _stdcall
Actived (void);
extern "C" __declspec(dllimport) int _stdcall Pro1
(void);
extern "C" __declspec(dllimport) int _stdcall Pro2
(void);
3.在OpenSample 后 你 就 可 以 使 用Delphi 中 的属 性Actived
、Pro1、Pro2
三: 参 考DLL Source 如 下:
library SampleDLL;
uses
SysUtils, Classes, Sample;
TYPE
TTempcomp = class(TComponent)
private
public
constructor Create1;
published
end;
var
Sample1 :Sample;
SaveExit :Pointer;
temp1 :TTempcomp;
constructor TTempcomp.Create1;
begin
// inherited Create(self);
end;
/==============================================
function OpenSample: Boolean; stdcall; export;
begin
HwCtrl:= Sample1.Create(temp1);
If Sample1.Actived then result:=true;
end;
procedure CloseSample; stdcall; export;
begin
Sample1.Destroy;
end;
function Actived: Boolean; stdcall; export;
begin
result:=Sample1.Actived;
end;
function Pro1: Interger; stdcall; export;
begin
result:= Sample1.Pro1;
end;
function Pro2: Interger; stdcall; export;
begin
result:= Sample1.Pro2;
end;
/==============================================
procedure libexit; far
begin
if Sample1.Actived =true then
Sample1.Destroy;
ExitProc:=SaveExit;
temp1.Destroy;
end;
exports
OpenSample,CloseSample,Actived ,Pro1,Pro2;
begin
temp1:=TTempcomp.Create1;
SaveExit:=ExitProc;
ExitProc:=@libexit;
end.
解 释:
因 为VCL 控 件 都 继 承 于TComponent,TComponent 的构 造 函 数需 要 一 个AOwner
并 且 也 是TComponent,VCL控 件 的Create、Destroy 都由 控 件 的 拥 有 者 来 动作,
也 就 是AOwner; 所 以 我 在 此DLL 中 新设 置 了 一 个TTempcomp 类 继 承 于Tcomponent
且 性 设 置 了 一个constructor(构 造 函 数)Create1, 而 实 际 构 造 时什 么 都 不 做,
以 次 作 为 要Create的Aowner;
其 他 还 有 一 种 办 法 就 是 用Application 作为Aowner 但 是 它是 基 于Tform 的 作 出 来 的DLL 太 大;
其 实,Inprise( 原 Borland) 尽 可 以 象MicroSoft 一 样 用 一些 象DCOM 类 似 的 组 件 形 式 使 得 产 品 在 同 一 产 品 时 代 保 持 一定 的 互 用 性, 来 增 加 产 品 群 的 生 命 力.