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

时间:2012-06-20 21:33:51

标签: c++ delphi dll delphi-7

我有一个我编写的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. 
}

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

我从这个问题的帮助中获得Delphi application calling a simple exposed c++ DLL functions

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

我的问题是:

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

1 个答案:

答案 0 :(得分:11)

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

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

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

然后您可以使用该类型来定义DLL函数:

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

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

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

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

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

RegisterCallbackGetProperty(Callback);
相关问题