1

I'm using Delphi 5. I define an array of byte, as follows:

Buffer: Array of BYTE;

How to convert it to a PByte pointer?

2 Answers 2

6

A dynamic array is implemented as a pointer, so you can simply type-cast it as-is:

var
  Buffer: array of Byte;
  P: PByte;
begin
  SetLength(Buffer, ...);
  P := PByte(Buffer);
  ...
end;

If you don't want to rely on this implementation detail, you can instead take the memory address of the 1st byte in the array:

P := @Buffer[0];
Sign up to request clarification or add additional context in comments.

2 Comments

But beware of the possible range-check exception if Buffer[0] doesn't exist.
Thank you. I modify my question to describe the case in more details. If I use PByte(Buffer) in MyFun, I will get compiler error "Invalid cast". With PByte(@Buffer[0]) is OK. Why?
6

Two ways to do this:

var
  P: PByte;
....
P := @Buffer[0]; // no cast, compiler can check type safety
P := PByte(Buffer); // implementation detail, dynamic array variable is pointer to first element

Note that the former leads to a range error if range checking is enabled and the array is empty. Because of this I tend to prefer the latter, although you may criticise the direct pointer cast for lacking type safety.

6 Comments

Thanks. But I have two questions: 1) I remember the first byte in the array is the count of the items, so if I use PByte(Buffer), will the pointer actually point to the counter, instead of the first element? 2) I try to use Inspect in Delphi to see (@Buffer[0]) and get a correct address, however, when I use PByte(Buffer), I get "Expression Error", why?
First byte is not the counter. You are thinking of a shortstring. No compiler error here with the cast. The debugger may not be able to evaluate it but there's not much you can do about that short of upgrading.
Thank you. I modify my question to describe the case in more details. If I use PByte(Buffer) in MyFun, I will get compiler error "Invalid cast". With PByte(@Buffer[0]) is OK.
I rolled back the question. You asked originally about a dynamic array. However, your edit talks about an open array. These are very different things, and so I rolled back the edit because it's too late to change the question after you have two answers. However, for an open array you have to use @Buffer[0].
OK. I see. Thank you very much. Originally I think they are the same thing so I just write a short version of my question. Sorry about that.
|

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.