2

Some time ago I needed to convert Array of Byte type to TBytes, which was done with help of delphi gurus here on SO;

Specifically, I needed to convert data so that I could extract what UDPServer gave me on ServerUDPRead in Indy 10.

This function was made by @David Heffernan, and is posted on this topic: Delphi XE3 indy compatibility issue between tbytes and tidbytes

So, I'm using

function CopyBytes(const Bytes: array of Byte): TBytes;
var
  Count: Integer;
begin
  Count := Length(Bytes);
  SetLength(Result, Count);
  if Count > 0 then
    Move(Bytes[0], Result[0], Length(Bytes));
end;

to convert this to TBytes and as one I can then send this type via Client UDP SendBuffer.

However, I need to make some modifications to data between they are forwarded; I read first line of array of byte which the ServerUDPRead delivers, to a string with this:

var FirstString: string;

FirstString := PAnsiChar(@AData[0]);

Where AData is array of byte;

Now, how could I do reverse conversion, so that I can put my own string to this AData array of byte instead of the one that is currently there, but without modifying any other data inside of the array, and then convert it to TBytes?

Is there a way to put something like AData[0]:=PAnsiChar(mystring); (this one is wrong, of course...) and then convert it with CopyBytes to TBytes, or maybe convert first to TBytes and then replace it there...?

Either way would be useful.

Community
  • 1
  • 1
That Marc
  • 1,134
  • 3
  • 19
  • 42
  • You can modify any part of this at any step of the way. I'm a little unclear on precisely what modification you are trying to make. You just want to copy some bytes into a byte array right? – David Heffernan Mar 25 '14 at 11:51
  • Actually, the FirstString would need to be changed; So, I'd like to change/replace some bytes in byte array, yes. – That Marc Mar 25 '14 at 12:13
  • You can use `Move` for that, just as appears in the `CopyBytes` function in your question – David Heffernan Mar 25 '14 at 12:19

1 Answers1

10

Indy has BytesToString() and ToBytes() functions for converting between String and TIdBytes. And if you are using Indy 10.6+, the IIdTextEncoding interface has GetBytes() and GetString() overloads that take PByte parameters, so you can use TBytes and array of Byte arrays without having to copy to/from TIdBytes.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770