views:

158

answers:

2

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?

+3  A: 

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.

gbjbaanb
Thanks. I did this and it prints out correctly: pHardcodedMsg:= '123'#0;CopyMemory(pMsg, pHardcodedMsg, Length(pHardcodedMsg)+1);
seveleven
-1 for "Delphi does not use NULL-terminated strings". Delphi strings are NULL-terminated and there is no need to add terminating 0 - it is already there. All you need is to use 4 characters instead of 3.
Serg
Delphi strings are not null terminated (a null does not terminate the string). But you are right in the sense that strings and literals have a null after the string content. It might not be the first one though.
Marco van de Voort
Delphi string ARE null-terminated. Delphi does not RELY on a null character at the end of the string, but it does somewhat enforce that MyString[Length(MyString) + 1] = #0. And although Delphi doesn't rely on the null itself, it does rely on the fact that there *should* be a null in every Windows API call. So if you go change the null character delphi appends to the string, you are in for quite a few problems.
Ken Bourassa
+1  A: 

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

Joe Meyer
1) when set to :='123', it is already allocated memory.
seveleven