6

I'm writing an ActiveX control for my friend, that should encapsulate encryption routines. It will be used from VB6 primarily. What data type should I choose for binary data like encryption key, initialization vector, input and output data so that it would be convenient for my friend to use it from VB6?

I'm using Delphi 7 to write this ActiveX, if that matters. One choice is to use hexadecimal strings. What can be the other?

Vladislav Rastrusny
  • 29,378
  • 23
  • 95
  • 156

1 Answers1

4

VB6 Binary data stored in Byte variables and arrays.

Dim arrData() As Byte

VB6 Application should pass that variable to your Delphi COM as OleVariant. Delphi COM can convert VarArray to TStream and vice versa:

procedure VariantToStream(const v :OleVariant; Stream: TStream);
var
  p : pointer;
  lo, hi, size: Integer;
begin
  lo := VarArrayLowBound(v,  1);
  hi := VarArrayHighBound (v, 1);
  if (lo >= 0) and (hi >= 0) then
  begin
    size := hi - lo + 1;
    p := VarArrayLock (v);
    try
      Stream.WriteBuffer (p^, size);
    finally
      VarArrayUnlock (v);
    end;
  end;
end;

procedure StreamToVariant(Stream: TStream; var v: OleVariant);
var
  p : pointer;
  size: Integer;
begin
  size := Stream.Size - Stream.Position;
  v := VarArrayCreate ([0, size - 1], varByte);
  if size > 0 then
  begin
    p := VarArrayLock (v);
    try
      Stream.ReadBuffer (p^, size);
    finally
      VarArrayUnlock (v);
    end;
  end;
end;

Usage in the CoClass unit:

// HRESULT _stdcall BinaryTest([in] VARIANT BinIn, [out, retval] VARIANT * BinOut );
function TMyComClass.BinaryTest(BinIn: OleVariant): OleVariant; safecall;
var
  Stream: TMemoryStream;
begin
  Stream := TMemoryStream.Create;
  try
    VariantToStream(BinIn, Stream);
    Stream.Position := 0;

    // do something with Stream ...

    // ... and return some Binary data to caller (* BinOut)
    Stream.Position := 0;
    StreamToVariant(Stream, Result);
  finally
    Stream.Free;
  end;
end;

This is the most common approach to use SAFEARRAY of Bytes with Binary data via COM automation.
Stuffing the data into a BSTR (Hex strings, Base64 Encoding etc..) sound kinda ugly to me and seems more like a hack.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
kobik
  • 21,001
  • 4
  • 61
  • 121
  • 2
    It is possible to put binary data into a `BSTR` without encoding it. The COM API has `SysAllocStringByteLen()` and `SysStringByteLen()` functions for working with binary `BSTR`s. This is not a hack, but it is not a commonly used feature. A `SAFEARRAY` containing `VT_UI1` elements is a better choice for passing around binary data, though (`IStream` is even better). – Remy Lebeau Feb 15 '12 at 01:47
  • @RemyLebeau-TeamB, Thanks for the info and edit :) I was referring to a hack by *encoding* the `BSTR`. – kobik Feb 15 '12 at 09:46