Delphi DLL – GetBytesPtr (Writing PByte to TStream)

Chilkat v9.5.0.80 adds a new BinData function named GetBytesPtr.   It returns a pointer to the internal bytes contained within the BinData.   This post shows one way of writing those bytes to a Delphi TStream (using the Chilkat non-ActiveX Delphi DLL).

procedure TForm1.Button2Click(Sender: TObject);
var
  rawBytes: PByte;
  ItemCount: Integer;
  binDat: HCkBinData;

  Stream: TMemoryStream;
  Writer: TBinaryWriter;
  byteArr: TBytes;
  numBytes: Integer;
  i: Integer;

begin
  binDat := CkBinData_Create();
  // Append 3 bytes (00, 01, and 02) to the CkBinData object.
  CkBinData_AppendEncoded(binDat, '000102', 'hex');

  // Return pointer to raw bytes (internal data) as a System.PByte
  // Your application does not own the data.  If you do something
  // to the binDat, such as append more data, or Clear(), then
  // your pointer to the bytes will become invalid.
  rawBytes := CkBinData_getBytesPtr(binDat);

  numBytes := CkBinData_getNumBytes(binDat);
  SetLength(byteArr, numBytes);

  // Create a type of TStream and write the bytes to it.
  Stream := TMemoryStream.Create;
  try
    Writer := TBinaryWriter.Create(Stream);
    try
      for i := 0 to (numBytes - 1) do
      begin
        Writer.Write(rawBytes^);
        Inc(rawBytes);
      end;
    finally
      Writer.Free;
    end;
  finally
    Stream.Free;
  end;

end;