views:

1887

answers:

4

what i have works, but im looking if there is a faster way to copy a string into a pByteArray

from sysutils

  PByteArray = ^TByteArray;
  TByteArray = array[0..32767] of Byte;

assume a and s are setup correctly

 a:   pByteArray;
 s:   string;

is there a fast way to do this, ie something like copy

  for i := 1 TO Length(s) - 1 do
   a^[i] := Ord(s[i]);

delphi 7

+1  A: 

never mind, found it

 Move(s[1], a^, Length(s));
Christopher Chase
Remember to check Length(s) <= SizeOf(a), or you risk a buffer overflow - a string may be bigger than a TByteArray.
ldsandon
A: 

I think you can use move procedure just like in this example

Michał Niklas
A: 

You can simply cast it:

  a := @s[1];

The other way around is:

  s := PChar(a);
Remko
That doesn't copy anything, and it makes `a` point to something that isn't what its type says it is.
Rob Kennedy
True (I assumed the purpose was to access the a string as a bytearray or vice vera)
Remko
+4  A: 

Beware using the Move. If you are using Delphi 2009, it may fail. Instead, use this:

Move(s[1], a^, Length(s) * SizeOf(Char));

You may also use class TEncoding in SysUtils.pas (Delphi 2009/2010++ only) to perform the task.

Chau Chee Yang
The for loop doesn't execute if length(s) is zero. To be fully equivalent you need to add a check for if length(s). Added.
Marco van de Voort