Delphi和C ++结构

时间:2018-10-12 09:37:14

标签: 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;

2 个答案:

答案 0 :(得分:1)

_PMyStruct->name=cstr.data();仅使指针指向字符串主体。但是在函数调用之后,应处置本地对象 std::string。因此,您已经获得了指向某个具有不可预测内容的内存地址的指针,如果内存不属于应用程序,则可能会导致AV。

似乎您必须分配内存和调用功能,以复制所需的数据到该内存地址。在需要时释放此内存。

答案 1 :(得分:0)

_MyStruct::name的定义更改为const char *,并为其指定文字。

请注意,以_开头的名称和大写字母的名称保留给实现,因此整个程序的行为都不确定。

您不需要typedef struct

struct MyStruct
{ 
    const char* name; // mutable pointer to constant char(s)
    // other fields
};

using PMyStruct = * MyStruct;

extern "C" __declspec(dllexport) __cdecl void MyTestStr(PMyStruct pMyStruct)
{
    pMyStruct->name = "string";
}

通常情况下,不建议跨dll边界传递拥有的指针。相反,caller should allocate和函数将复制到该分配中。这是Win32Api上使用的模式。您可以返回尺寸,也可以使用int *参数将尺寸写入

C ++ Dll

extern "C" __declspec(dllexport) __cdecl void MyTestStr(PMyStruct pMyStruct = nullptr, int * firstname_size = nullptr, int * lastname_size = nullptr)
{
    if (pMyStruct)
    {
        std::strncpy(pMyStruct->firstname, "string", pMyStruct->firstname_len);
        std::strncpy(pMyStruct->lastname, "other string", pMyStruct->lastname_len);
    }
    if (firstname_size) { *firstname_size = 7; }
    if (lastname_size) { *lastname_size = 13; }
}

Delphi exe

type
  PInteger = ^Integer;
  PMyStruct = ^MyStruct;
  MyStruct= record
    firstname : PAnsiChar;
    firstname_len : Integer;
    lastname : PAnsiChar;
    lastname_len : Integer;
    // other fields
  end;

procedure MyTestStr(pMyStruct: PMyStruct; firstname_len : PInteger; lastname_len : PInteger); cdecl; external 'mytest.dll' name 'MyTestStr';   

procedure TestMyRec();
var
  myStruct: MyStruct;
begin
// If you don't know how much memory you will need, you have to ask
  MyTestStr(nil, @myStruct.firstname_len, @myStruct.lastname_len); 
  GetMem(myStruct.firstname, myStruct.firstname_len);
  GetMem(myStruct.lastname, myStruct.lastname_len);

  MyTestStr(@myStruct); 

  // Use myStruct

  FreeMem(myStruct.firstname);
  FreeMem(myStruct.lastname);
end;