PDA

View Full Version : How to get a string from a buffer



{MSX}
04-09-2007, 08:36 AM
This is something i never remember..
If i have a buffer (ie, a pointer and a size), how do i obtain a string?

function BufferToString(prt:pointer; size:cardinal):string;
begin
result:=???
end;

Setharian
04-09-2007, 08:42 AM
function BufferToString(Src: Pointer; Size: Integer): AnsiString;
begin
SetLength(Result, Size);
Move(Src^, Pointer(Result)^, Size);
end;

{MSX}
04-09-2007, 11:11 AM
ah perfect :P i'll try to keep it in mind!

JSoftware
04-09-2007, 03:13 PM
function BufferToString(Src: Pointer; Size: Integer): AnsiString;
begin
SetLength(Result, Size);
Move(Src^, Pointer(Result)^, Size);
end;
Looks a little fishy to me. This might compile and work but isn't it a bit c-ish. What type will a pointer have when dereferenced? Yes, I know Move works with untyped parameters but I still don't like it. I would rather write it like this:

function BufferToString(Src: Pointer; Size: Integer): AnsiString;
begin
SetLength(Result, Size);
Move(PByteArray(Src)^[0], Result[1], Size);
end;

Wouldn't Pointer(Result)^ be incorrect too? (Pointer(Result[1])^)?

Edit: Excuse me my nosy-ness. I've been programming C for 16 hours :shock:

Setharian
04-09-2007, 04:46 PM
It will compile down to the same code. Your code will just cause a bigger headache for the compiler. :)