How to copy a DWord Size Data from a array of Byte and conver to DWord type Value in Delphi?

Viewed 392

I'm trying to convert the C++ code snippet below to Delphi:

DWORD n;
memcpy(&n, lpData, sizeof(n)); <==== the C++ data type : LPBYTE lpData = NULL; 
wprintf(L"REG_DWORD - ValueName: %s, Data: %u\n", pValueName, n);

I do not know the Delphi part, I've tried some code as below:

lpData: array of byte;
n : DWord;
// then do not know how to use 
procedure CopyMemory(Destination: Pointer; Source: Pointer; Length: NativeUInt);

Here is the most difficult part to me:

  1. I don't know how to convert lpData to a pointer.

  2. variable Destination type is PByte, or not?

  3. How to get the length?

  4. How to convert the destination value to n (Dword type value)?

2 Answers

Dynamic array is already pointer, so the next code works:

var
  lpData: array of byte;
  n : DWord;
begin
  lpData := [$0A, $0B, $0C, $0D];
  CopyMemory(@n, lpData, SizeOf(n));
  Caption := Format('%x', [n]);

Note that lpData should be initialized.

Also array of byte; is doubtful analog of C++ data type - it is Delphi-specific managed type. Array body might be used as storage, but overall usage might differ.

Direct analog of LPBYTE is Delphi PByte, sometimes PByteArray is convenient. It is worth to describe - how your lpData is filled.

Probably the easiest way to deal with this is to use a cast.

var
  lpData: PByte;
  n: DWORD;
... 
n := PDWORD(lpData)^;
Related