What data type is suitable to handle binary data in ActiveX method?

妖精的绣舞 提交于 2020-01-22 15:17:25

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9265884/what-data-type-is-suitable-to-handle-binary-data-in-activex-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!