关于GetTextBuf(Buffer: PChar; BufSize: Integer)中的BufSize(34分)

  • 主题发起人 主题发起人 sqlserver2
  • 开始时间 开始时间
S

sqlserver2

Unregistered / Unconfirmed
GUEST, unregistred user!
function TControl.GetText: TCaption;
var
Len: Integer;
begin
Len := GetTextLen;
SetString(Result, PChar(nil), Len);
if Len <> 0 then GetTextBuf(Pointer(Result), Len + 1);//len是长度,为什么这里是len + 1;
end;
 
delphi的帮助里

var
Buffer: PChar;
Size: Byte;
begin
Size := Edit1.GetTextLen; {Get length of string in Edit1}
Inc(Size); {Add room for null character}
GetMem(Buffer, Size); {Creates Buffer dynamic variable}
Edit1.GetTextBuf(Buffer,Size); {Puts Edit1.Text into Buffer}
Edit2.Text := StrPas(Buffer); {Converts Buffer to a Pascal-style string}
FreeMem(Buffer, Size);{Frees memory allocated to Buffer}
end;

----------------
Inc(Size); {Add room for null character}??????????
 
if Len <> 0 then GetTextBuf(Pointer(Result), Len + 1);//len是长度,为什么这里是len + 1;
result为tcaption,那么存放的是string类型的,而string和pchar类型的转换过程中前者第一个字节存放的的长度信息,所以要加一才符合吧。
//没有调试过。
 
应该是这样:
An application sends a WM_GETTEXTLENGTH message to determine the length, in characters, of the text associated with a window. The length does not include the terminating null character
WM_GETTEXTLENGTH消息取的长度不包含最后的结束符,而这里的字符串很有可能还要与系统
进一步交流,根据下面这段话,可能需要0结束符会好一点
ms-help://borland.bds4/bds4ref/html/StringTypes.htm#AboutStrings
Working with null-Terminated Strings
Many programming languages, including C and C++, lack a dedicated string data type. These languages, and environments that are built with them, rely on null-terminated strings. A null-terminated string is a zero-based array of characters that ends with NUL (#0); since the array has no length indicator, the first NUL character marks the end of the string. You can use Delphi constructions and special routines in the SysUtils unit (see Standard routines and I/O ) to handle null-terminated strings when you need to share data with systems that use them.

For example, the following type declarations could be used to store null-terminated strings.
type
TIdentifier = array[0..15] of Char;
TFileName = array[0..259] of Char;
TMemoText = array[0..1023] of WideChar;
With extended syntax enabled ({$X+}), you can assign a string constant to a statically allocated zero-based character array. (Dynamic arrays won't work for this purpose.) If you initialize an array constant with a string that is shorter than the declared length of the array, the remaining characters are set to #0.
 
GetTextBuf(Pointer(Result), Len + 1);String-〉PChar 指针地址的长度要加1,所谓#0结束符。
 
接受答案了.
 
后退
顶部