IntPtr IntPtr can also represent all pointer and string types, in which case you need to manually marshal data using the Marshal class. When working with functions that receive a text buffer, the StringBuilder class provides the easiest solution. The following example shows how to use a StringBuilder to receive a text buffer: function GetText(Window: HWND; BufSize: Integer = 1024): string;
var
Buffer: StringBuilder;
begin
Buffer := StringBuilder.Create(BufSize);
GetWindowText(Window, Buffer, Buffer.Capacity);
Result := Buffer.ToString;
end;
The StringBuilder class is automatically marshaled into an unmanaged buffer and back. In some cases it may not be practical, or possible, to use a StringBuilder . The following examples show how to marshal data to send and retrieve strings using SendMessage: procedure SetText(Window: HWND; Text: string);
var
Buffer: IntPtr;
begin
Buffer := Marshal.StringToHGlobalAuto(Text);
try
Result := SendMessage(Window, WM_SETTEXT, 0, Buffer);
finally
Marshal.FreeHGlobal(Buffer);
end;
end;
An unmanaged buffer is allocated, and the string copied into it by calling StringToHGlobalAuto. The buffer must be freed once it’s no longer needed. To marshal a pointer to a structure, use the Marshal. StructureToPtr method to copy the contents of the structure into the unmanaged memory buffer. The following example shows how to receive a text buffer and marshal the data into a string: function GetText(Window: HWND; BufSize: Integer = 1024): string;
var
Buffer: IntPtr;
begin
Buffer := Marshal.AllocHGlobal(BufSize * Marshal.SystemDefaultCharSize);
try
SendMessage(Window, WM_GETTEXT, BufSize, Buffer);
Result := Marshal.PtrToStringAuto(Buffer);
finally
Marshal.FreeHGlobal(Buffer);
end;
end;
It is important to ensure the buffer is large enough, and by using the SystemDefaultCharSize method, the buffer is guaranteed to hold BufSize characters on any system. Advanced Techniques When working with unmanaged API’s, it is common to pass parameters as either a pointer to something, or NULL. Since the managed API translations don’t use pointer types, it might be necessary to create an additional overloaded version of the function with the parameter that can be NULL declared as IntPtr . Special Cases There are cases where a StringBuilder and even the Marshal class will be unable to correctly handle the data that needs to be passed to an unmanaged function. An example of such a case is when the string you need to pass, or receive, contains multiple strings separated by
文章整理:西部数码--专业提供域名注册、虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!