繁体   English   中英

Delphi dll function 到 C#

[英]Delphi dll function to C#

使用已编译的 Delphi dll,声明的函数之一是

Mydll.dll

type
 TInfo = array [0..255] of byte;

type
 public
   function GetInfo(Memadr, Infolen: Integer): TInfo;

在 C# 中使用的 DLLImport 格式是什么?

我会这样做:

Delphi

type
  TInfo = array [0..255] of byte;

procedure GetInfo(Memadr, Infolen: Integer; var Result: TInfo); stdcall;

C#

[DllImport(@"testlib.dll")]
static extern void GetInfo(int Memadr, int Infolen, byte[] result);

static void Main(string[] args)
{
    byte[] result = new byte[256];
    GetInfo(0, result.Length, result);
    foreach (byte b in result)
        Console.WriteLine(b);
}

您需要使调用约定匹配。 我已经选择了stdcall ,这是 P/invoke 的默认设置(这就是为什么在 P/invoke 签名中没有指定它的原因)。

我会避免将数组作为 function 返回值返回。 以这种方式将其编组为参数更容易。

事实上,一般来说,如果你想摆脱固定大小的缓冲区,你可以这样做:

Delphi

procedure GetInfo(Memadr, Infolen: Integer; Buffer: PByte); stdcall;

然后,要填充缓冲区,您需要使用一些指针算法或等效的东西。

需要纠正我原来帖子中的一个错误,

type
 TInfo = array [0..255] of byte;

implementation
 function GetInfo(Memadr, Infolen: Integer): TInfo;


procedure TForm1.Button5Click(Sender: TObject);
var Data: TInfo;
    i: integer;
    s: string;
begin
for i:=0 to 255 do Data[i]:=0;
Data:=GetInfo($04,12);
if (Data[1]=0) then
  begin StatusBar1.SimpleText:='No Data'; exit; end;
s:='';
for i:=1 to 8 do
  s:=s+Chr(Data[i+1]);
Edit3.Text:=s;
end;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM