【问题标题】:Calling a callback function in Delphi from a C++ DLL从 C++ DLL 调用 Delphi 中的回调函数
【发布时间】:2012-06-23 02:53:53
【问题描述】:

我有一个我编写的 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 函数可以使用函数指针。

【问题讨论】:

    标签: c++ delphi dll delphi-7


    【解决方案1】:

    在 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多