将Delphi DLL函数导入C ++ Builder,传输PAnsiChar

用户名

我想使用Delphi代码,从C ++ Builder通过DLL导出

Delphi代码片段是这样的

//  function declare 
function NameData(ItemIndex: Integer;
  Buffer: PAnsiChar; var BufSize: DWORD): DWORD; stdcall;
  external 'database.dll' 


// function calling code 
  s1, S2: AnsiString;
begin


  for i := 1 to  ...  do
  begin
    BufSize := 0;
    NameData(i, nil, BufSize);
    SetLength(s1, BufSize);
    NameData(i, PAnsiChar(s1), BufSize);

    mmo_dll.lines.Add(' name ->  ' + string(s1));

相关的DLL代码

library DLLCode; 


function NameData(ItemIndex: Integer;
  Buffer: PAnsiChar; var BufSize: DWORD): DWORD; stdcall;
var
  returnString: Ansistring;
begin
  returnString := ' call some other functions .....';

  if BufSize < Length(returnString) then
    result := ERROR_BUFFER_TOO_SMALL
  else
  begin
    StrPCopy(Buffer, returnString);
    result := ERROR_NO_ERROR;
  end;
  BufSize := Length(returnString);
end;

Delphi和Delphi DLL可以很好地解决这个问题。现在这是我无法正常工作的C ++代码:

//  function prototype 
typedef void (__stdcall*IntCharIntIn_VoidOut)(int, PAnsiChar, int);

// DLL prototype 
extern "C" __declspec(dllimport)
    IntCharIntIn_VoidOut  __stdcall NameData(int, PAnsiChar, int);

//  instance declaration 
IntCharIntIn_VoidOut   NameData;


//  load library data, no error raise,  other simpler function call already working

........
NameData = (IntCharIntIn_VoidOut)::GetProcAddress(load,
            "NameData");


///  calling code 
    int  Bufsize;
    PAnsiChar DataName;


    for (i = 0; i < count - 1; i++) {

        *Bufsize = 0;

        NameData(i, NULL, Bufsize);

        StrLen(SignalName);

        NameData(i, DataName, Bufsize );


        Memo1->Lines->Add(IntToStr(i));  // for test only 
    }

在第二个电话中,我遇到访问冲突,但是看不到我为什么/在哪里错

大卫·赫弗南(David Heffernan)

您不分配任何内存,并且函数声明错误。

该函数的确应该这样声明:

typedef void (__stdcall *IntCharIntIn_VoidOut)(int, char*, unsigned int*);

您的调用代码应为:

unsigned int Bufsize;
char* DataName;

for (i = 0; i < count - 1; i++) {
    Bufsize = 0;
    NameData(i, NULL, &Bufsize);
    DataName = new char[Bufsize + 1];
    NameData(i, DataName, &Bufsize);
    // do something with DataName
    delete[] DataName;
}

我已经省略了对内存分配和释放的错误检查。如果是我,我会使用长大的C ++字符串对象,而不是原始内存。循环看起来好像错过了最后的迭代,应该<= count - 1还是< count肯定的。您的类型名称IntCharIntIn_VoidOut无法识别两个参数是指针。我使用的char*不是PAnsiChar,但我想后者只是前者的别名。

我将上述所有内容留给您处理。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章