From: "Peter Below (TeamB)" <100113.1101@compuXXserve.com> Subject: Re: passing strings Date: 24 Jun 1999 00:00:00 GMT Message-ID: Content-Transfer-Encoding: 8bit References: <3772243A.2D3A@kmc-controls.com> Content-Type: text/plain; charset=iso-8859-1 Organization: TeamB Mime-Version: 1.0 Reply-To: 100113.1101@compuXXserve.com Newsgroups: borland.public.delphi.objectpascal > I have finally been able to pass a string TO my BCB DLL routine to a > calling app in Delphi with the following code : > > (BCB) > extern "C" __declspec( dllexport ) __stdcall void test( char* ); > void __stdcall test( char* InputBuffer ) > (Delphi) > procedure test( InputBuffer : String ); > stdcall; external 'MyDLL.dll'; No, you do this wrong, sorry. A Delphi String (AnsiString) is NOT equivalent to a C char*. It happens to work if the string is only read by the C side since AnsiStrings are always zero-terminated (but the #0 at end does not define the length, there is a length dword at negative offsets to the string pointer) and a AnsiString variable is a pointer that points at the first character, but will break if the routine tries to write to the character buffer since that not only circumvents the reference counting mechanism but also has the potential to write beyond the end of buffer. Build your function like the API does for functions like GetWindowsDirectory: you pass them a buffer pointer (PChar) and the size of the buffer, so the routine can guard against overwriting. procedure Test( inputbuffer: PChar; buffersize: Integer ); stdcall; external .... You use this like you would an API function from delphi: Var S: String; Begin SetLength( S, 512 ); Test( PChar(S), Length(S)); SetLength( S, StrLen( PChar(S)); The Test routine is required to zero-terminate its result if it is shorted than 512 characters. It can leave off the #0 if it copies exactly 512 characters since there is an extra #0 at S[513] (not a legal index!) added by the Delphi string management. Peter Below (TeamB) 100113.1101@compuserve.com) No e-mail responses, please, unless explicitly requested!