Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert data types to call a COM procedure?

I have a procedure that I need to call using COM, which is declared like this in C#:

void DoSomething (string param1, string[] param2, Object[] param3)

The Delphi declaration in the imported TypeLibrary is:

procedure DoSomething (param1: System.Widestring, 
                       param2: ActiveX.PSafeArray, 
                       param3: ActiveX.PSafeArray);

param1 is just a string.
param2 is an array of argument names, let's say: ['arg1', 'arg2'].
param3 is the according values for these arguments.

Example: arg1: Double = 1.23, arg2: integer = 10.
This will result in:
- param2: ['arg1', 'arg2']
- param3: [1.23, 10]

So far, I have this code to convert param2[] into a PSafeArray:

var param2: array of string;
    i: integer;
    va_param2: Variant;
    psa_param2: Activex.PSafeArray;
begin
  SetLength (param2, 2);
  param2 [0] := 'arg1';
  param2 [1] := 'arg2';
  // Create VariantArray, copy data
  va_param2 := VarArrayCreate ([0, Length(param2)-1], varOleStr);
  for i := 0 to Length(param2)-1 do
    va_param2 [i] := param2 [i];
  // Convert VariantArray to PSafeArray
  psa_param2 := PSafeArray (TVarData (va_param2).VArray);
end;

Now I should have the PSafeArray for param2.
But how can I do this for param3[] ?
There will be different data types, not only strings.

Since I cannot call the COM procedure before param2 and param3 are set up, I can also not be sure if the above code is doing what I need.
It runs, but am I doing these conversions correctly for passing the result to the above COM procedure?

like image 924
Holgerwa Avatar asked Jan 17 '23 11:01

Holgerwa


1 Answers

By default, a .NET Object is marshaled as a COM VARIANT, unless explicitally specified as an IUnknown or IDispatch in the C# code using MarshalAs syntax.

Try this:

var
  param2: array of string; 
  param3: array of Variant; 
  i: integer; 
  va_param2: Variant; 
  va_param3: Variant; 
  psa_param2: Activex.PSafeArray; 
  psa_param3: Activex.PSafeArray; 
begin 
  SetLength (param2, 2); 
  param2 [0] := 'arg1'; 
  param2 [1] := 'arg2'; 

  SetLength (param3, 2);
  param3[0] := 1.23;
  param3[1] := 10;

  // Create arrays, copy data 

  va_param2 := VarArrayCreate ([Low(param2), High(param2)], varOleStr); 
  for i := Low(param2) to High(param2) do 
    va_param2 [i] := param2 [i]; 

  va_param3 := VarArrayCreate ([Low(param3), High(param3)], varVariant); 
  for i := Low(param3) to High(param3) do 
    va_param3 [i] := param3 [i]; 

  // Convert arrays to PSafeArray 

  psa_param2 := PSafeArray (TVarData (va_param2).VArray); 
  psa_param3 := PSafeArray (TVarData (va_param3).VArray); 

  ...
end; 
like image 137
Remy Lebeau Avatar answered Jan 30 '23 21:01

Remy Lebeau