问题
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);
回答1:
the first thing i can remember is SafeArrayCreate
.
have a look at 'mysteries of PSafeArray'
回答2:
This code works fine:
function GetObjects: PSafeArray;
var
aBounds: array [0..0] of TSafeArrayBound;
aObjects: PSafeArray;
aIndex: Integer;
aConnectionObject: OleVariant;
aCashConnection: OleVariant;
aScript: OleVariant;
begin
aBounds[0].lLbound := 0;
aBounds[0].cElements := 3;
aObjects := SafeArrayCreate(varVariant, 1, @aBounds);
aIndex := 0;
aConnectionObject := ADOConnection.ConnectionObject;
OleCheck(SafeArrayPutElement(aObjects, aIndex, aConnectionObject));
aIndex := 1;
aCashConnection := CashConnection;
OleCheck(SafeArrayPutElement(aObjects, aIndex, aCashConnection));
aIndex := 2;
aScript := Self as IDispatch;
OleCheck(SafeArrayPutElement(aObjects, aIndex, aScript));
Result := aObjects;
end;
来源:https://stackoverflow.com/questions/10788939/how-to-create-a-parameter-of-type-psafearray