我有一个需要使用COM调用的过程,在C#中声明如下: public string ali(int[] num){ string r; r =""; foreach (int a in num) { r = r + Convert.ToString(a) + ";"; } return r;} 导入的TypeLibrary中的Delphi声明是: function
public string ali(int[] num) { string r; r =""; foreach (int a in num) { r = r + Convert.ToString(a) + ";"; } return r; }
导入的TypeLibrary中的Delphi声明是:
function TSqr.ali(num: PSafeArray): WideString; begin Result := DefaultInterface.ali(num); end;
我有这个代码将整数数组转换为PSafeArray:
Function ArrayToSafeArray2 (DataArray: array of integer):PSafeArray; var SafeArray: PSafeArray; InDataLength,i: Integer; vaInMatrix: Variant; begin InDataLength := Length(DataArray); vaInMatrix := VarArrayCreate([Low(DataArray), High(DataArray)], varInteger); for i:= Low(DataArray) to High(DataArray) do begin vaInMatrix[I] := DataArray[I]; end; SafeArray := PSafeArray(TVarData(vaInMatrix).VArray); Result := SafeArray; VarClear(vaInMatrix); SafeArrayDestroy(SafeArray); end;
这个代码调用我的COM函数
var a:array of integer; Answer:String; begin SetLength(a,3); a[0] := 1; a[1] := 2; a[2] := 2; Answer := Sqr1.ali(ArrayToSafeArray2(a)); ShowMessage(Answer); end;
但错误发生:
“带有消息的EOLeExeption’排名为0的SafeArray已传递给期望排名为1的数组的方法……”
我该怎么办?
在调用者可以使用之前,您的转换例程正在销毁SafeArray.与Delphi数组不同,COM数组不是引用计数.在将SafeArray传递给COM过程之后,不要销毁它,例如:function ArrayToSafeArray2 (DataArray: array of integer): Variant; var i: Integer; begin Result := VarArrayCreate([Low(DataArray), High(DataArray)], varInteger); for i:= Low(DataArray) to High(DataArray) do begin Result[I] := DataArray[I]; end; end;
.
var a:array of integer; v: Variant; Answer:String; begin SetLength(a,3); a[0] := 1; a[1] := 2; a[2] := 2; v := ArrayToSafeArray2(a); Answer := Sqr1.ali(TVarData(v).VArray); ShowMessage(Answer); end;