c++ - Delphi 和 C++ 结构

标签 c++ delphi

我有以下 C++ 函数,它导出一个结构,其中包含一个 char* 字段,但在 Delphi 中使用时,字符串值并不像预期的那样,尽管它是空终止的。

typedef struct _MyStruct{
    char* name;
    // other fields
}MyStruct,*PMyStruct;

extern "C" __declspec(dllexport) __cdecl MyTestStr(PMyStruct _PMyStruct)
{
    std::string str = "string";
    std::vector<char> cstr(str.begin(), str.end);
    cstr.push_back('\0');//null-terminated
    _PMyStruct->name = cstr.data();    
}
type
  PMyStruct = ^MyStruct;
  MyStruct= record
    name : PAnsiChar;
        // other fields
  end;

procedure MyTestStr(_PMyStruct: PMyStruct); cdecl; external 'mytest.dll' name 'MyTestStr';    

procedure TestMyRec();
var
  _MyStruct: MyStruct;
begin
  MyTestStr(@_MyStruct); 
  showmessage(_MyStruct.name);
  // here the result is just 'YYYYYYYYYYYYYYYYYY' not 'string'
end;

最佳答案

_PMyStruct->name=cstr.data(); 只是指向字符串主体。但是在函数调用之后 local object std::string 应该被处理掉。所以你有指向一些内容不可预测的内存地址的指针,如果内存不属于应用程序,这可能会导致 AV。

似乎您必须分配内存并调用复制所需数据到该内存地址的函数。需要时释放此内存。

关于c++ - Delphi 和 C++ 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52776637/

相关文章:

c++ - 缺少 Visual Studio 2019 C++ 外部依赖项

c++ - 尽管有大量可用内存,但 malloc() 失败

multithreading - 为什么显示弹出菜单时不调用Application.OnMessage?

delphi - 在 Delphi 中重命名 DLL

delphi - 对于使用 Delphi ObjectPascal 的 GUI,在(可能)更改它之前检查 .Visible 是否有任何有用的目的?

c++ - libjingle的XmppPump编译问题

c++ - typedef shared_ptr<T> 转换为 bool

c++ - 模板类型推导失败(std::empty 作为谓词)

windows - SetTimer 生成一个随机的 IDEvent

delphi - 使用delphi加载ntuser.dat hive