seveleven
seveleven

Reputation: 707

Passing PChar / *char between C++ and Delphi DLL

I have a C++ program, that calls Delphi DLL to initialize a buffer that contains chars.

I am testing out the interface to make sure the data are passed correctly:

In C++ program:

char * pMsg = (char*)malloc(3); //allocate buffer

Init(pMsg * char); //Delphi DLL function

In Delphi DLL:

procedure Init(pMsg:PChar);
var
  pHardcodedMsg:PChar;
begin
  pHardcodedMsg:= '123';
  CopyMemory(pMsg, pHardcodedMsg, Length(pHardcodedMsg));
end;

But, when I try to printf( (const char*)pMsg ) in C++, It shows me "123" followed by some rubbish characters.

Why is this so? How can I successfully place an array of char into the buffer and have the string printed out correctly?

Upvotes: 1

Views: 5417

Answers (2)

Joe Meyer
Joe Meyer

Reputation: 448

Your Init function doesn't work because

1) pHardcodedMsg is a pointer for which you didn't allocate memory

2) CopyMemory doesn't add a 0 to the end of pMsg

3) the procedure header of Init misses a semi colon at the end of the line

When you are using a unicode version of Delphi you will also have to consider string length and character set conversion

Upvotes: 1

gbjbaanb
gbjbaanb

Reputation: 52689

Delphi does not use NULL-terminated strings so you need to slap a 0 at the end, as C/C++ uses that to determine where the string data ends (Pascal uses the size of the string at the beginning IIRC).

The usual character is '\0' - escape value 0.

Don't forget to return 4 characters, not 3.

Upvotes: 4

Related Questions