<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
</head>
<body>
<p style="margin: 0;">
<span>
<span></span>
</span>
</p>
<p style="margin: 0px;"></p>
<div style="margin: 5px 0px 5px 0px;">
<br/>
Felipe Monteiro de Carvalho <felipemonteiro.carvalho@gmail.com> hat am 19. Oktober 2011 um 09:13 geschrieben:
<br/>
<br/>
> Hello,
<br/>
>
<br/>
> Usually when we work with PChars we do things like this to set the
<br/>
> final terminator:
<br/>
>
<br/>
> var
<br/>
> ansistr: ansistring;
<br/>
> begin
<br/>
> // Copy the originating string taking into account the specified length
<br/>
> SetLength(ansistr, len+1);
<br/>
> System.Move(source^, ansistr[1], len);
<br/>
> ansistr[len+1] := #0;
<br/>
> SetLength(ansistr, len);
<br/>
>
<br/>
> And it works fine. You get a string with correct length and a final #0
<br/>
> terminator.
</div>
<p style="margin: 0px;"> </p>
<p style="margin: 0px;">I never saw such code for ansistring. Only for shortstring. </p>
<p style="margin: 0px;">SetLength(ansistring) already allocates memory for the header+len+1, creates the header and sets the len+1 character to #0. </p>
<p style="margin: 0px;">Simply do:</p>
<p style="margin: 0px;"> SetLength(ansistr, len);</p>
<p style="margin: 0px;">
if len>1 then
<br/>
System.Move(source^, ansistr[1], len);
</p>
<p style="margin: 0px;"> </p>
<div style="margin: 5px 0px 5px 0px;">
>
<br/>
> Now, I simply tryed the same code for a unicodestring, and it corrupts my stack:
<br/>
>
<br/>
> procedure Unicode2AnsiMove(source:pwidechar;var dest:ansistring;len:SizeInt);
<br/>
> var
<br/>
> widestr: unicodestring;
<br/>
> begin
<br/>
> {$ifdef PASWSTRING_VERBOSE}WriteLn('Unicode2AnsiMove START');{$endif}
<br/>
> // Copy the originating string taking into account the specified length
<br/>
> SetLength(widestr, len+1);
<br/>
> System.Move(source^, widestr[1], len*2);
<br/>
> PWideChar(@widestr)[len] := #0; // <--- This corrupts the stack
</div>
<p style="margin: 0px;"> </p>
<p>This would corrupt the stack for ansistring too. This would only work for shortstring.</p>
<p>widestr is a unicodestring is a pointer to widechar. </p>
<p> </p>
<p> PWideChar(widestr)[len] := #0; </p>
<p> </p>
<p style="margin: 0px;"> </p>
<div style="margin: 5px 0px 5px 0px;">
> SetLength(widestr, len);>
<br/>
> I already fixed the problem by simply not setting this last widechar
<br/>
> to #0, but now I got puzzled: Any ideas why this doesn't work?
<br/>
>
<br/>
> It crashes only a bit after this procedure, but I found that this was
<br/>
> the statement which caused the problem.
</div>
<div></div>
<div>Mattias</div>
<div></div>
</body>
</html>