简体   繁体   English

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

[英]Calling a callback function in Delphi from a 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.我有一个我编写的 C++ DLL,它有一个公开的函数,它将函数指针(回调函数)作为参数。

#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. 
}

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.我希望能够从 Delphi 应用程序中调用这个公开的 C++ DLL 函数并注册回调函数以供将来使用。 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.我有Delphi 应用程序从我在这个问题中得到的帮助调用了一个简单的公开的 c++ DLL 函数

I am building the C++ DLL and I can change its parameters if needed.我正在构建 C++ DLL,如果需要,我可以更改其参数。

My questions are:我的问题是:

  • How to I create a function pointer in Delphi如何在 Delphi 中创建函数指针
  • How to I correctly call the exposed C++ DLL function from within a Delphi application so that the C++ DLL function can use the function pointer.如何从 Delphi 应用程序中正确调用公开的 C++ DLL 函数,以便 C++ DLL 函数可以使用函数指针。

Declare a function pointer in Delphi by declaring a function type.在 Delphi 中通过声明函数类型来声明函数指针。 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;

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.请注意,调用约定是cdecl因为您的 C++ 代码没有指定调用约定,而 cdecl 是 C++ 编译器通常的默认调用约定。

Then you can use that type to define the DLL function:然后您可以使用该类型来定义 DLL 函数:

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

Replace 'dllname' with the name of your DLL.'dllname'替换为您的 DLL 的名称。

To call the DLL function, you should first have a Delphi function with a signature that matches the callback type.要调用 DLL 函数,首先应该有一个带有与回调类型匹配的签名的 Delphi 函数。 For example:例如:

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

Then you can call the DLL function and pass the callback just as you would any other variable:然后,您可以调用 DLL 函数并像处理任何其他变量一样传递回调:

RegisterCallbackGetProperty(Callback);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM