Delphi: how to call ActiveX Functions that return an OleVariant containing a Byte Array
Some Chilkat ActiveX functions return binary data as a Variant containing a byte array. If the Chilkat function fails, it returns an OleVariant containing an empty byte array. The following code snippet is incorrect and will cause Delphi to raise an EVariantBadIndexError exception if an empty OleVariant is returned.
// This is incorrect: mybuffer : array of byte; // ... // Do not directly assign a variable declared as "array of byte" to the OleVariant returned // by the Chilkat function. mybuffer := socket.ReceiveBytes();
The correct technique is to do the following:
myVariant: OleVariant; myByteArray : array of byte; uBound : Integer; numBytes : Integer; // .... myVariant := socket.ReceiveBytes(); // Check the upper bound of the array contained within the Variant. // If it equals -1, then it is empty which means the Chilkat function call failed. uBound := VarArrayHighBound( myVariant, 1 ); if (uBound < 0) then begin Memo1.Lines.Add(socket.LastErrorText); Exit; end; // The number of bytes in the byte array equals uBound+1 numBytes := uBound+1; // Now that we know the variant is non-empty, it is safe to access it as an "array of byte" myByteArray := myVariant;
admin
0
Tags :