PDA

View Full Version : Pointers to strings



NecroDOME
27-05-2007, 12:32 PM
System: Windows XP
Compiler: Turbo Delphi
Api: Plane windows...

Hi there,

So Im trying to make pointer to a string like this:


// first set the length of teh string
SetLength(String(ValuePointer), Length(s)+1);

// Now copy new data into my string
CopyMemory(ValuePointer, @s[1], Length(s));

ValuePointer is a pointer to a valid string, s is the data I need to copy into my value pointer. Ths piece of code works, but not all the time strangely.
How come?

JSoftware
27-05-2007, 12:50 PM
try it like this:

CopyMemory(pointer(cardinal(ValuePointer)+1), @s[1], Length(s));

I think that a normal string stores the length in the first byte. I'm not sure though

NecroDOME
27-05-2007, 01:06 PM
well, if I ditch the +1 after cardinal(ValuePointer) than it seems to work :) thnx

Setharian
27-05-2007, 04:54 PM
that doesn't make sense, only shortstrings store length in their first byte.....
the problem is in the SetLength call, you set it to have length 1 bigger than the original string...no need for that if ValuePointer is also of type string, such thing is needed only if it is a PChar (in which case you'd use GetMem/ReallocMem instead)....and rather use Move than CopyMemory, it just calls Move anyways and you don't have to include windows in the uses clause...

SetLength(string(ValuePointer), Length(s));
Move(s[1], ValuePointer^, Length(s));

Edit:
or maybe an even better way to do it would be this...

string(ValuePointer) := s;
UniqueString(string(ValuePointer));

savage
27-05-2007, 05:00 PM
Can I ask why you would rather use a string in this case and not a PChar or PWideChar?

NecroDOME
27-05-2007, 10:07 PM
its not only about strings, but also integers and other classes.

However I figured out it is not the best method to use a direct pointer to the value I want to set.

First I wanna to change a var directly, but I think its a better approach for me to use 2 procs, 1 get, 1 set. (however I still use pointers).
Its needed cause I may need to do some more actions when I set a var to a new value.

(it's a bit hard to explain, but I hope you can understand :S )