2

假设我在 C++ 中有一个函数,我在其中使用指向其内存地址的指针调用它,并使用typedef. 现在,我怎样才能在 Delphi 中做同样的事情?

例如:

typedef void (*function_t)(char *format, ...);
function_t Function;
Function = (function_t)0x00477123;

然后,我可以用:Function("string", etc);.

在 Delphi 中,有没有办法在不使用汇编指令的情况下做到这一点?

请注意,它是一个可变参数函数。

4

3 回答 3

17

一个惯用的翻译:

typedef void (*function_t)(char *format, ...);
function_t Function;
Function = (function_t)0x00477123;

这是:

type
  TFunction = procedure(Format: PAnsiChar) cdecl varargs;
var
  Function: TFunction;
// ...
  Function := TFunction($00477123);

'cdecl varargs' 是获取 C 调用约定(调用者弹出堆栈的地方)和可变参数支持(仅支持 C 调用约定)所必需的。Varargs 仅支持作为调用 C 的一种方式;Delphi 中没有内置支持以 C 风格实现可变参数列表。相反,有一种不同的机制,由 Format 过程和朋友使用:

function Format(const Fmt: string; const Args: array of const): string;

但您可以在其他地方找到更多相关信息。

于 2010-01-27T22:15:36.583 回答
2
program Project1;

type
  TFoo = procedure(S: String);

var
  F: TFoo;
begin
  F := TFoo($00477123);
  F('string');
end.

当然,如果您只是运行上述程序,您将在地址 $00477123 处收到运行时错误 216。

于 2010-01-27T20:22:03.187 回答
1

是的,Delphi 支持函数指针。像这样声明它:

type MyProcType = procedure(value: string);

然后声明一个 MyProcType 类型的变量并将你的过程的地址分配给它,你可以像在 C 中一样调用它。

如果你想要一个指向对象方法而不是独立过程或函数的指针,请在函数指针声明的末尾添加“对象”。

于 2010-01-27T20:21:43.880 回答