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

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
4

You can simply cast it:

  a := @s[1];

The other way around is:

  s := PChar(a);

2 Comments

That doesn't copy anything, and it makes a point to something that isn't what its type says it is.
True (I assumed the purpose was to access the a string as a bytearray or vice vera)
2

never mind, found it

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

1 Comment

Remember to check Length(s) <= SizeOf(a), or you risk a buffer overflow - a string may be bigger than a TByteArray.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.