是否可以(不使用运行时软件包或共享内存DLL)在主机应用程序和DLL模块之间传递Record类型,其中Record类型包含函数/过程(Delphi 2006及更高版本)?
让我们假设为了简单起见我们的Record类型不包含任何String字段(因为这当然需要Sharemem DLL),这里是一个例子:
TMyRecord = record
Field1: Integer;
Field2: Double;
function DoSomething(AValue1: Integer; AValue2: Double): Boolean;
end;
所以,简单地说明一下:我可以在主机应用程序和DLL(在任一方向)之间传递TMyRecord的“实例”,而无需使用运行时包或共享内存DLL,并从两者执行DoSomething函数主机EXE和DLL?
答案 0 :(得分:7)
我不会建议,无论它是否有效。如果您需要DLL在TMyRecord
个实例上运行,最安全的选择是让DLL导出普通函数,例如:
DLL:
type
TMyRecord = record
Field1: Integer;
Field2: Double;
end;
function DoSomething(var ARec: TMyRecord; AValue1: Integer; AValue2: Double): Boolean; stdcall;
begin
...
end;
exports
DoSomething;
end.
应用:
type
TMyRecord = record
Field1: Integer;
Field2: Double;
end;
function DoSomething(var ARec: TMyRecord; AValue1: Integer; AValue2: Double): Boolean; stdcall; external 'My.dll';
procedure DoSomethingInDll;
var
Rec: TMyRecord;
//...
begin
//...
if DoSomething(Rec, 123, 123.45) then
begin
//...
end else
begin
//...
end;
//...
end;
答案 1 :(得分:4)
如果我理解你的问题,那么你可以做到,这是一种方法:
testdll.dll
library TestDll;
uses
SysUtils,
Classes,
uCommon in 'uCommon.pas';
{$R *.res}
procedure TakeMyFancyRecord(AMyFancyRecord: PMyFancyRecord); stdcall;
begin
AMyFancyRecord^.DoSomething;
end;
exports
TakeMyFancyRecord name 'TakeMyFancyRecord';
begin
end.
uCommon.pas< - 由应用程序和dll使用,用于定义您的花哨记录的单位
unit uCommon;
interface
type
PMyFancyRecord = ^TMyFancyRecord;
TMyFancyRecord = record
Field1: Integer;
Field2: Double;
procedure DoSomething;
end;
implementation
uses
Dialogs;
{ TMyFancyRecord }
procedure TMyFancyRecord.DoSomething;
begin
ShowMessageFmt( 'Field1: %d'#$D#$A'Field2: %f', [ Field1, Field2 ] );
end;
end.
最后是测试应用程序,文件 - >新的 - > vcl表单应用程序,在表单上放一个按钮,在uses子句中包含uCommon.pas,添加对外部方法的引用
procedure TakeMyFancyRecord(AMyFancyRecord: PMyFancyRecord); stdcall;
external 'testdll.dll' name 'TakeMyFancyRecord';
并在按钮的点击事件中添加
procedure TForm1.Button1Click(Sender: TObject);
var
LMyFancyRecord: TMyFancyRecord;
begin
LMyFancyRecord.Field1 := 2012;
LMyFancyRecord.Field2 := Pi;
TakeMyFancyRecord( @LMyFancyRecord );
end;
<强>声明:强>
享受!
David Heffernan'编辑
为了100%清除,执行的DoSomething方法是DLL中定义的方法。 EXE中定义的DoSomething方法永远不会在此代码中执行。