Calling a callback function in Delphi from a C++ DLL

淺唱寂寞╮ 提交于 2019-12-11 15:14:01

问题


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

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.

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

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

My questions are:

  • How to I create a function pointer in 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.

回答1:


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;

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.

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

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

Replace 'dllname' with the name of your DLL.

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;

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

RegisterCallbackGetProperty(Callback);


来源:https://stackoverflow.com/questions/56707554/calling-a-delphi-method-from-a-c-dll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!