在Delphi中正确调用外部dll?

时间:2015-01-01 19:25:03

标签: delphi dll usb i2c ftdi

我知道很少有Delphi的基础知识(事实上我已经使用它几年了)......

我正在用DLL砸墙(从来没有真正玩过这个)。

考虑这个例子:

   unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

Type FT_Result = Integer;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;


var
  Form1: TForm1;
  FT_HANDLE : DWord = 0;



implementation

{$R *.dfm}

function I2C_GetNumChannels(numChannels: dword):FT_Result; stdcall; external 'libmpsse.dll' name 'I2C_GetNumChannels';
function I2C_OpenChannel(index:dword;handle:pointer):FT_Result; stdcall; external 'libmpsse.dll' name 'I2C_OpenChannel';

procedure TForm1.Button1Click(Sender: TObject);
var
numofchannels:dword;
begin
i2c_getnumchannels(numofchannels);
showmessage(inttostr(numofchannels));
end;

end.

我需要从FTDI连接libmpsse.dll以访问USB端口上的I2C设备 当我调用函数I2C_GetNumChannels时,我得到了大量的AccessViolation ......

我只是想知道dll函数有什么问题?

此外,I2C_GetNumChannels应返回2个值......

enter image description here

从官方API指南 - > http://www.ftdichip.com/Support/Documents/AppNotes/AN_177_User_Guide_For_LibMPSSE-I2C.pdf

非常感谢!

此致

1 个答案:

答案 0 :(得分:4)

您的翻译不正确。它应该是:

function I2C_GetNumChannels(out numChannels: Longword): FT_Result;
  stdcall; external 'libmpsse.dll';

您正在调用的函数接受32位无符号整数的地址。您的翻译按值传递了32位无符号整数。

您可以使用指针翻译导入,但调用者可以使用varout参数更轻松地执行此操作,就像我所做的那样。

我假设您已正确确定调用约定为stdcall。您需要检查头文件才能确定。

您应该检查函数调用返回的值是否有错误。这是人们调用外部库时最常见的错误。不要忽略返回值。检查错误。