我有一个用C ++编写的DLL。我想从Delphi 7中调用一个函数。
我只有一个用VB.NET编写的示例。
在发布到这里之前,我已经尝试过自己转换代码。
问题是当我调用函数时,它给我二进制输出错误,这显然意味着我对输入做错了。
这是VB.NET中的原始代码:
Private Shared Declare Unicode Function Read_Write Lib "Subway.dll" (obej As IntPtr, Data_in As Byte(), in_siz As Integer, <Out()> ByRef Data_out As IntPtr, ByRef out_siz As Integer) As Integer
Dim obej As IntPtr = IntPtr.Zero
Dim Data_out As IntPtr = 0
Dim out_siz As Integer = 0
Dim Res As Integer = -1
Res = Read_Write(obej, Encoding.[Default].GetBytes(Mystr), Mystr.Length, Data_out, out_siz)
我在Delphi中转换后的代码:
function Read_Write(obej: Pointer; Data_in: TByteDynArray; in_siz:Cardinal; var Data_out: TByteDynArray; var out_siz: Cardinal): Integer; stdcall; external 'Subway.dll';
var
tx, rx: TByteDynArray;
obej: pointer;
s:string;
Res: Integer;
out_siz: Integer;
SetLength(tx, Length(s));
Move(s[1], tx[0], Length(s));
Res := Read_Write(obej, tx, length(s), rx, out_siz);
普通电话(C语言):
int __stdcall Read_Write(void *u_arg, const unsigned char *p_data_in, unsigned int data_in_len, unsigned char **pp_data_out, unsigned int *p_data_out_len);
答案 0 :(得分:2)
您的Read_Write()
的Delphi声明与VB.NET声明不匹配。您没有考虑.NET如何将参数编组为非托管语言。另外,TByteDynArray
是特定于Delphi的类型,您不能原样传递给其他语言,尤其是在输出参数中。
请尝试以下类似操作:
function Read_Write(obej: Pointer; Data_in: PByte; in_siz: Integer, var Data_out: Pointer; var out_siz: Integer): Integer; stdcall; external 'Subway.dll';
var
obej: Pointer;
Data_out: Pointer;
out_siz: Integer;
Res: Integer;
MyStr: AnsiString;
buf: TByteDynArray;
begin
...
obej := nil;
Data_out := nil;
out_siz := 0;
MyStr := ...;
SetLength(buf, Length(MyStr));
Move(PAnsiChar(MyStr)^, PByte(buf)^, Length(MyStr));
Res := Read_Write(obej, PByte(buf), Length(buf), Data_out, out_siz);
// use Data_out up to out_siz bytes as needed...
// free Data_out as needed...
...
end;
或者,您可以省略TByteDynArray
并直接跳过AnsiString
数据:
Res := Read_Write(obej, PByte(PAnsiChar(MyStr)), Length(MyStr), Data_out, out_siz);