Delphi Binary Data
This post shows some code snippets for getting data from Delphi Byte arrays (TBytes) and TMemoryStream’s in and out of Chilkat. First, here are some code snippets to convert from a TMemoryStream to a byte array, and back.Delphi TBytes to TMemoryStream
var
iStream: TMemoryStream;
b: TBytes;
OpFile: String;
numBytes: Cardinal;
begin
// Load a file into bytes
OpFile := 'C:\qa_data\certs\cert_test123.cer';
b := nil;
numBytes := FileToBytes(OpFile, b);
if (numBytes > 0) then
begin
// Byte array to TMemoryStream
iStream := TMemoryStream.Create;
iStream.Write(b[0], Length(b));
...
<h4>Delphi TMemoryStream to TBytes</h4>
<pre>
var
iStream: TMemoryStream;
b: TBytes;
...
...
// TMemoryStream to byte array.
iStream.Seek(0, soBeginning);
SetLength(b, iStream.Size);
iStream.Read(Pointer(b)^, Length(b));
...
</pre>
<h4>Load Delphi TBytes into Chilkat BinData</h4>
<pre>
var
b: TBytes;
hData: HCkBinData;
pointerToBytes: PByte;
...
begin
...
...
hData := CkBinData_Create();
pointerToBytes := PByte(b);
CkBinData_AppendBinary2(hData,pointerToBytes,Length(b));
</pre>
<h4>Write contents of Chilkat BinData to a TStream</h4>
<pre>
var
rawBytes: PByte;
hData: HCkBinData;
Stream: TMemoryStream;
Writer: TBinaryWriter;
i: Integer;
numBytes: Integer;
begin
hData:= CkBinData_Create();
// Append 3 bytes (00, 01, and 02) to the CkBinData object.
CkBinData_AppendEncoded(hData, '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 hData, such as append more data, or Clear(), then
// your pointer to the bytes will become invalid.
rawBytes := CkBinData_getBytesPtr(hData);
numBytes := CkBinData_getNumBytes(hData);
// 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;
</pre>
admin
0
Tags :