How convert byte array to variant?

Dippen
Dippen used Ask the Experts™
on
Hi!
I need to convert x bytes of data allocated by GetMem to a OleVariant so I can send it to and from a DCOM-server. How is the best way to solve this?

Regards, Daniel
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Software Engineer, Advisory
Top Expert 2005
Commented:

Daniel,

Here is sample code that will create a variant array or byte that you can pass. Just need to pass the pointer, size of data, and the ole variant to hold the array on return. The result (on success) will come back as S_OK, anything else is a OLE failure.

Russell


// Make sure to include ActiveX in your uses clause

function BuffToVariant(P: Pointer; Size: Cardinal; var VarResult: OleVariant): HResult;
var  sab:        TSafeArrayBound;
     psa:        PSafeArray;
     pba:        Pointer;
begin

  // Set the starting bound and element count for the array
  sab.lLbound:=0;
  sab.cElements:=Size;

  // Create the safe array
  psa:=SafeArrayCreate(VT_UI1, 1, sab);

  // Make sure we got an array
  if Assigned(psa) then
  begin
     // Access the data
     result:=SafeArrayAccessData(psa, pba);
     // Make sure success
     if (result = S_OK) then
     begin
        // Copy the bytes to the safe array.
        CopyMemory(pba, P, Size);
        // Unaccess the data
        SafeArrayUnaccessData(pba);
        // Set type to array of unsigned char
        TVariantArg(VarResult).vt:=VT_ARRAY or VT_UI1;
        TVariantArg(VarResult).parray:=psa;
        // Set success
        result:=S_OK;
        // Exit out
        exit;
     end;
     // Cleanup array on failure
     if Assigned(psa) then SafeArrayDestroy(psa);
  end
  else
     // Failed to allocate the array
     result:=E_OUTOFMEMORY;

end;

Author

Commented:
Thx alot! I will try this code as soon as possible and get back to you!
type
  PArrayData = ^TArrayData;
  TArrayData = array[0..9] of Byte;
var
  A: Variant;
  P: PArrayData;
  BA: TArrayData;
begin
  A := VarArrayCreate([0, 9], varByte);
  P := VarArrayLock(A);
  try
    Move(P^[0], A[0], SizeOf(Byte)*Length(BA)) ;
  finally
    VarArrayUnlock(A);
  end;
end;

try something like that. Here A - your variant array and
BA you destination byte array

Author

Commented:
Thx alot for your help, both of you. I'm accepting rllibby's answer, partly because you answered first and partly because your solution looks a bit more slick to me.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial