我试图弄清楚如何从 DLL 中调用应用程序中的过程(而不是如何调用 DLL 中的过程)。应用程序和DLL都是用Delphi 11开发的。
procedure DrawRectangle( X, Y, W, H: Integer );
var
MyRect: TRectangle;
begin
MyRect := TRectangle.Create( mainForm );
//and so on...
end;
DrawRectangle( 10, 10, 100, 100 );
任何有关简单示例的帮助将不胜感激。我在网上搜索并阅读了几篇文章,但仍然无法掌握如何完成我想做的事情。
这就像一般设置回调一样。只需将编写 DLL 与定义过程类型结合起来:
library Lib;
type
// The callback must be defined type as procedure or function,
// so the compiler knows all parameters and the calling convention.
// The name is only relevant to the type, not the procedure.
TProcDrawRectangle= procedure( X, Y, W, H: Integer ); stdcall;
var
// The pointer which either got something assigned to call or not.
ProcToCall: TProcDrawRectangle= nil;
// We call this to pass (the pointer to a) procedure which this DLL
// can later call on its own to execute the procedure elsewhere.
procedure LinkMyCallback( proc: TProcDrawRectangle ); stdcall;
begin
ProcToCall:= proc;
end;
// However, when/where the callback is executed is up to you.
procedure OtherThings(); stdcall;
begin
//...
if Assigned( ProcToCall ) then ProcToCall( 10, 20, 800, 600 );
end;
exports
LinkMyCallback,
OtherThings;
begin
end.
现在在您的程序中执行相同的操作,并导入 DLL 的过程:
program Main;
type
// The same definition as in the library, of course. Naturally you would put this
// once in a unit, which is then used by both: your program and the DLL.
TProcDrawRectangle= procedure( X, Y, W, H: Integer ); stdcall;
// Statically linking the procedure (or functions) which are exported by the library.
procedure LinkMyCallback( proc: TProcDrawRectangle ); stdcall; external 'Lib.dll';
procedure OtherThings(); stdcall; external 'Lib.dll';
// Will be called from the library.
procedure CallbackHere( X, Y, W, H: Integer ); stdcall;
begin
//DrawRectangle( X, Y, W, H: Integer );
end;
begin
// Hand over (a pointer to) the procedure which it wants to call
// at a later time.
LinkMyCallback( CallbackHere );
// Now is a "later time": executing this library's procedure will in
// turn call on the DLL side the procedure pointer, which is then
// executing "CallbackHere()" in this program.
OtherThings();
end.
留意使用相同的调用约定制作所有导出的过程/函数 - Delphi 与
stdcall
配合使用效果最佳。避免使用仅 Delphi 类型,如 String
或一般的类/对象 - 更好地使用简单类型和辅助函数来间接操作对象。使用 DLL 时该做什么和不该做什么是另一个主题。