5

是否有可能(不使用运行时包或共享内存 DLL)在主机应用程序和记录类型包含函数/过程(Delphi 2006 及更高版本)的 DLL 模块之间传递记录类型?

为了简单起见,我们假设我们的 Record 类型不包含任何 String 字段(因为这当然需要 Sharemem DLL),下面是一个示例:

TMyRecord = record
  Field1: Integer;
  Field2: Double;
  function DoSomething(AValue1: Integer; AValue2: Double): Boolean;
end;

所以,简单地说:我可以在主机应用程序和 DLL 之间传递一个 TMyRecord 的“实例”(在任一方向),而不使用运行时包或共享内存 DLL,并从主机 EXE 执行 DoSomething 函数和DLL?

4

2 回答 2

7

我不建议这样做,无论它是否有效。如果您需要 DLL 对TMyRecord实例进行操作,最安全的选择是让 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; 
于 2011-12-08T02:09:47.267 回答
4

如果我正确理解了您的问题,那么您可以做到,这是一种方法:

测试dll.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;

免责声明:

  • 工作于 D2010;
  • 在我的机器上编译!

请享用!


大卫赫弗南编辑

为了 100% 清楚,执行的 DoSomething 方法是 DLL 中定义的方法。EXE 中定义的 DoSomething 方法永远不会在此代码中执行。


于 2011-12-08T02:29:44.207 回答