【问题标题】:Convert C++ callback function to Delphi将 C++ 回调函数转换为 Delphi
【发布时间】:2019-02-28 00:01:29
【问题描述】:

我需要帮助将这个 C++ 头文件翻译成 Delphi。

它是一个回调函数原型,还有一些内联函数(我不清楚它们为什么会存在,因为它们似乎没有被使用)。

源 .h 代码:

// This file defines 'myStreamWriter_t' a function pointer type.
// The user of the C API need to specify a callback of above type which
// will be called on xxx_print(...) with the formatted data.
// For C++ API, a default callback is specified which writes data to
// the stream specified in xxx::print

typedef int(*myStreamWriter_t)(const char* p1,
                                     int p2,
                                     void *p3);

上面很简单:应该翻译成Delphi,如下:

type
   myStreamWriter_t = function(const p1:Pchar; 
                                     p2:integer;
                                     p3:pointer):integer;


现在,还有一些我不知道如何翻译的东西:

源 .h 代码:

#include <ostream>

namespace ns1 {
namespace ns2 {

inline int OstreamWriter(const char *p1, int p2, void *p3);

struct StreamProxyOstream {

static int writeToStream(const char* p1, int p2, void *p3);
    // Format, to the specified 'p3' stream, which must be a pointer to a
    // 'std::ostream', the specified 'p2' bytes length of the specified 'p1' data.
};


inline
int StreamProxyOstream::writeToStream(const char *p1,
                                      int         p2,
                                      void       *p3)
{
    reinterpret_cast<std::ostream*>(p3)->write(p1, p2);
    return 0;
}

inline
int OstreamWriter(const char *p1, int p2, void *p3)
{
    return StreamProxyOstream::writeToStream(p1, p2, p3);
}

}  // close namespace ns2
}  // close namespace ns1

...上面的Delphi怎么翻译??

非常感谢!

【问题讨论】:

    标签: c++ function delphi


    【解决方案1】:

    您的翻译不正确。应该是:

    type
      myStreamWriter_t = function(p1: PAnsiChar; p2: Integer; p3: Pointer): Integer cdecl;
    

    请注意,const char *x(指向 const 字符的非 const 指针)没有 Delphi 等效项,因此只需使用 PAnsiChar。在 2009 年以后的任何 Delphi 中,PChar 是 PWideChar,这不等同于 char *

    const x: PAnsiChar 等效于char * const x,这意味着 指针 是 const,而不是它指向的字符。

    你的调用约定很可能是错误的。

    同样,您应该翻译其他功能。但请注意,结构上的函数(方法)可能会以不同的方式调用,即使用 Microsoft 专有的方法约定(__thiscall)。没有与之对应的 Delphi。

    但无论如何,您可能无法在不遇到兼容性问题的情况下调用此类方法。 您可以模仿这些类/结构的行为,但您将无法使它们在 Delphi 中二进制兼容,除非您跳过几个环节和/或使用汇编程序.

    我的网站上的更多信息:

    如果您想模仿该行为,您可以执行以下操作:

     OstreamWriter(p1: AnsiChar; p2: Integer; p3: Pointer): Integer; // no need for binary compatibility, so you can omit cdecl
     begin
       TStream(p3).Write(p1^, StrLen(p1) + 1);
       TStream(p3).Write(p2, SizeOf(p2));
     end;
    

    但是您将不得不重写整个 C++ 代码。如果您已经对上面的代码有问题,这并不简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多