簡體   English   中英

將C ++回調函數轉換為Delphi

[英]Convert C++ callback function to Delphi

在將此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中翻譯?

非常感謝你!

您的翻譯不正確。 它可能應該是:

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

請注意,沒有與const char *x (指向const char *x非const指針)等效的Delphi,因此只需使用PAnsiChar。 在2009年以后的任何Delphi中,PChar都是PWideChar,這並不等同於char *

const x: PAnsiCharchar * const x等效,表示指針是const,而不是它指向的char。

而且您的呼叫約定很可能是錯誤的。

同樣,您應該翻譯其他功能。 但是請注意,結構上的函數(方法)可能會以不同的方式調用,即對方法使用專有的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 ++代碼。 如果上面的代碼已經有問題,這不是一件簡單的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM