Retrieve a string |
Top Previous Next |
PInvoke > Retrieve a string There are many API functions to retrieve strings. In these cases a buffer is passed which then is filled with characters. A C# string cannot be used as such a buffer, because it's internal buffer cannot be "pre-allocated". But StringBuilder can be used instead.
function GetTempPath(nBufferLength: DWORD; lpBuffer: LPWSTR): DWORD; stdcall; {$EXTERNALSYM GetTempPath}
implementation
function GetTempPath; external kernelbase name 'GetTempPathW';
becomes to:
[DllImport(kernelbase, SetLastError=true)] public static extern uint /*stdcall*/ GetTempPath( uint nBufferLength, StringBuilder lpBuffer);
public static uint /*stdcall*/ GetTempPath(uint nBufferLength, ref char[] lpBuffer) { StringBuilder tmp3 = new StringBuilder(lpBuffer.ToString(), lpBuffer.Length); uint tmp2 = GetTempPath(nBufferLength, tmp3); lpBuffer = tmp3.ToString().ToCharArray(); return tmp2; }
Delphi2C# creates an adapter function with a "ref char[]" parameter. This buffer must already have enough space for the retrieved characters. Correctly the first parameter nBufferLength should be used to set the size for the buffer, but Delphi2C# cannot know this from the pure syntax of the function. But if the original Delphi code works, then the generated C# code will work too.
If an API function has LPWSTR parameters Delphi2C# also creates a second adapter function with a string reference parameter instead of the character array reference:
public static uint /*stdcall*/ GetTempPath(uint nBufferLength, ref string lpBuffer) { // StringBuilder tmp1 = new StringBuilder(lpBuffer, lpBuffer.Length); StringBuilder tmp1 = new StringBuilder((int)nBufferLength); uint tmp0 = GetTempPath(nBufferLength, tmp1); lpBuffer = tmp1.ToString(); return tmp0; }
Here the same problem with the buffer size exist.The string has to have the required size before GettempPath is called and it will have this size, if the converted Delphi code had been correct.
char[] Path = new char[256]; uint ui = GetTempPath(256, ref Path);
string sPath = string.Empty; SetLength(ref sPath, 256); ui = GetTempPath(256, ref sPath);
|
This page belongs to the Delphi2C# Documentation |
Delphi2C# home Content |