我的 Delphi 应用程序正在从 C++ DLL 调用一个函数,该函数应该返回这样的字符串。

C++ DLL

__declspec( dllexport ) void sample(char* str1, char* str2)
{
    strcpy(str1, "123");
    strcpy(str2, "abc");
}

德尔福
procedure sample(Str1, Str2: pchar); cdecl; external 'cpp.dll';
var
  buf1 : Pchar;
  buf2 : Pchar;
begin
  sample(@buf1, @buf2);
  //display buf1 and buf2
  //ShowMessage(buf1); //it display random ascii characters
end;

这样做的正确方法是什么?

最佳答案

您需要为要写入的 C++ 代码分配内存。例如:

var
  buf1, buf2: array [0..255] of Char;
begin
  sample(buf1, buf2);
end;

您还应该重新设计您的接口(interface)以接受缓冲区的长度,从而允许 DLL 代码避免缓冲区溢出。

关于c++ - 如何使用字符串参数在 Delphi 中调用 C++ DLL?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22169178/

10-10 22:17