开发者

Need to allocate memory before a Delphi string copy?

开发者 https://www.devze.com 2023-01-02 09:57 出处:网络
Do I need to allocate memory when performing a Delphi string copy? I\'ve a function which posts a Windows message to another form in my application.It looks something like this:

Do I need to allocate memory when performing a Delphi string copy?

I've a function which posts a Windows message to another form in my application. It looks something like this:

// Note:  PThreadMessage = ^TThreadMessage; TThreadMessage = String;

function PostMyMessage( aStr : string );
var
  gMsgPtr : PT开发者_开发技巧hreadMessage;
  gStrLen : Integer;
begin
  New(gMsgPtr);
  gStrLen := StrLen(PWideChar(aMsg));
  gMsgPtr^ := Copy(aMsg, 0, gStrLen);
  PostMessage(ParentHandle, WM_LOGFILE, aLevel, Integer(gMsgPtr));

  // Prevent Delphi from freeing this memory before consumed.
  LParam(gMsgPtr) := 0;
end;


You don't need to allocate any memory. In fact, you don't even need to call Copy. A simple string assignment is sufficient; the reference count will be tracked correctly acorss multiple threads. You also don't need to clear gMsgPtr; since it's not a variable of type string, the compiler won't insert any cleanup code for it.

begin
  New(gMsgPtr);
  gMsgPtr^ := aMsg;
  PostMessage(ParentHandle, wm_LogFile, aLevel, LParam(gMsgPtr));
end;

If you want to call Copy anyway, you don't need to calculate the length first. It will automatically clamp the index parameters to the largest allowed range. When you want to ask for "rest of the string," you can simply pass MaxInt as the third parameter and Copy will know what to do. It likewise does that for the second parameter, automatically increasing any value to be at least 1, the lowest valid character index.


You don't need to allocate memory to copy strings, but you don't want to pass a pointer to a Delphi string in this situation. You want to pass a PChar, (AKA a C string,) and you do have to allocate memory for that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号