从 C++ DLL 调用 Delphi 中的回调函数

2021-12-25 00:00:00 dll c++ delphi delphi-7

我编写了一个 C++ DLL,它有一个公开的函数,它将函数指针(回调函数)作为参数.

I have a C++ DLL that I wrote that has a single exposed function, that takes a function pointer (callback function) as a parameter.

#define DllExport   extern "C" __declspec( dllexport )

DllExport bool RegisterCallbackGetProperty( bool (*GetProperty)( UINT object_type, UINT object_instnace, UINT property_identifer, UINT device_identifier, float * value ) ) {
    // Do something. 
}

我希望能够从 Delphi 应用程序中调用这个公开的 C++ DLL 函数并注册回调函数以供将来使用.但是我不确定如何在 Delphi 中创建一个可以与公开的 C++ DLL 函数一起使用的函数指针.

I want to be able to call this exposed C++ DLL function from within a Delphi application and register the callback function to be used at a future date. But I am unsure of how to make a function pointer in Delphi that will work with the exposed C++ DLL function.

我有 Delphi 应用程序调用一个简单的暴露的 c++ DLL功能 来自我在这个问题中得到的帮助.

I have the Delphi application calling a simple exposed c++ DLL functions from the help I got in this question.

我正在构建 C++ DLL,如果需要,我可以更改其参数.

I am building the C++ DLL and I can change its parameters if needed.

我的问题是:

  • 如何在 Delphi 中创建函数指针
  • 如何从 Delphi 应用程序中正确调用公开的 C++ DLL 函数,以便 C++ DLL 函数可以使用函数指针.

推荐答案

在 Delphi 中通过声明函数类型来声明函数指针.例如,您的回调函数类型可以这样定义:

Declare a function pointer in Delphi by declaring a function type. For example, the function type for your callback could be defined like this:

type
  TGetProperty = function(object_type, object_instnace, property_identifier, device_identifier: UInt; value: PSingle): Boolean; cdecl;

注意调用约定是 cdecl 因为你的 C++ 代码没有指定调用约定,而 cdecl 是 C++ 编译器通常的默认调用约定.

Note the calling convention is cdecl because your C++ code specified no calling convention, and cdecl is the usual default calling convention for C++ compilers.

然后你可以使用那个类型来定义DLL函数:

Then you can use that type to define the DLL function:

function RegisterCallbackGetProperty(GetProperty: TGetProperty): Boolean; cdecl; external 'dllname';

'dllname' 替换为您的 DLL 的名称.

Replace 'dllname' with the name of your DLL.

要调用 DLL 函数,首先应该有一个带有与回调类型匹配的签名的 Delphi 函数.例如:

To call the DLL function, you should first have a Delphi function with a signature that matches the callback type. For example:

function Callback(object_type, object_instnace, property_identifier, device_identifier: UInt; value: PSingle): Boolean cdecl;
begin
  Result := False;
end;

然后您可以调用 DLL 函数并传递回调,就像您处理任何其他变量一样:

Then you can call the DLL function and pass the callback just as you would any other variable:

RegisterCallbackGetProperty(Callback);

相关文章