Search code examples
c#delphicomdelphi-xe2typelib

How to create a parameter of type PSafeArray?


How to create a parameter of type PSafeArray?

I take the following error from C# COM library:

  SafeArray with range 65262 transfered to the method that requires array with range 1

Delphi XE2 should call C# COM library procedure using Generated RIDL type-library with a parameter of type PSafeArray.

Delphi XE2 code:

  function GetObjects: PSafeArray;
  var
    aObjects: Variant;
  begin
    aObjects := VarArrayCreate([0, 2], varVariant);
    aObjects[0] := ADOConnection.ConnectionObject;
    aObjects[1] := CashConnection;
    aObjects[2] := Self as IDispatch;
    Result := PSafeArray(TVarData(aObjects).VArray);
  end;

  ICompiler.Execute('MainNameSpace', 'MainClass', 'MainMethod', GetObjects);

C# COM library code:

void Execute(string Namespace, string ClassName, string MethodName, Object[] Objects);

void ICSCompiler.Execute(string Namespace, string ClassName, string MethodName, Object[] Objects)
{
  System.Type _type = cr.CompiledAssembly.GetType(Namespace + "." + ClassName);
  System.Object obj = Activator.CreateInstance(_type);
  System.Reflection.MethodInfo mi = obj.GetType().GetMethod(MethodName);
  mi.Invoke(obj, new Object[] { Objects });
}

Generated RIDL code:

HRESULT _stdcall Execute([in] BSTR Namespace, [in] BSTR ClassName, [in] BSTR MethodName, [in] SAFEARRAY(VARIANT) Objects);

Solution

  • the first thing i can remember is SafeArrayCreate. have a look at 'mysteries of PSafeArray'