从Delphi中的c ++ DLL调用函数

Ste*_*rst 12 c++ delphi dll delphi-7

我在VS2010中创建了一个新的c ++ DLL项目,它暴露了1个函数

#include "stdafx.h"    
#define DllImport   extern "C" __declspec( dllimport )
#define DllExport   extern "C" __declspec( dllexport )    
DllExport int DoMath( int a, int b) {
    return a + b ; 
}
Run Code Online (Sandbox Code Playgroud)

然后我用VS2010创建了一个C++应用程序来测试这个DLL.在VS2010中构建的测试应用程序可以调用c ++ DLL并获得预期的结果.

#include "stdafx.h"
#include <windows.h>

typedef int (*DoMath)(int, int) ; 
int _tmain(int argc, _TCHAR* argv[])
{
    HMODULE hMod = LoadLibrary ("exampleDLL.dll");
    if (NULL != hMod) {
        DoMath mf1 = (DoMath) GetProcAddress(hMod,"DoMath");
        if( mf1 != NULL ) {
            printf ("DoMath(8,7)==%d \n", mf1(8,7) );   
        } else {
            printf ("GetProcAddress Failed \n");
        }
        FreeLibrary(hMod);
    } else { 
        printf ("LoadLibrary failed\n");
        return 1;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

接下来,我尝试在Delphi 7中构建一个新项目来调用这个C++ DLL.我用这个教程来帮助我构建新项目.

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

type
  TmyFunction = function(X,Y: Integer):Integer;

  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    procedure FormShow(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    hDll: THandle;
  end;

var
  Form1: TForm1;
  fDoMath : TmyFunction;

implementation
{$R *.dfm}

procedure TForm1.FormShow(Sender: TObject);
begin
  hDll := LoadLibrary('exampleDLL.dll');
   if HDll >= 32 then { success }
   begin
     fDoMath := GetProcAddress(hDll, 'DoMath');
   end
   else
     MessageDlg('Error: could not find exampleDLL.DLL', mtError, [mbOk], 0)
end;

procedure TForm1.Button1Click(Sender: TObject);
 var i: Integer;
begin
 i := fDoMath(2,3);
 edit1.Text := IntToStr(i);
end;
end.
Run Code Online (Sandbox Code Playgroud)

Delphi 7项目的结果是6155731当我预计5.我检查了结果的二进制文件,认为它可能与数据类型有关,但对我来说它看起来是随机的.当我重新编译/重新运行应用程序时,它每次都会得到相同的结果.

我不太了解德尔福,这是我第一次处理它,我发现它令人困惑.

关于接下来要检查什么的任何建议?

Dav*_*nan 18

您需要指定调用约定,在本例中为cdecl:

TMyFunction = function(X, Y: Integer): Integer; cdecl;
Run Code Online (Sandbox Code Playgroud)

您的代码使用默认的Delphi调用约定,它register通过寄存器传递参数.该cdecl调用约定堆栈传递参数,所以这种不匹配解释了为什么在两个模块之间的通信失败.


还有一些评论:

失败模式LoadLibrary是返回NULL,即0.检查而不是返回值>=32.

使用隐式链接导入此函数更简单.用这个简单的声明替换所有LoadLibraryGetProcAddress代码:

function DoMath(X, Y: Integer): Integer; cdecl; external 'exampleDLL.dll';
Run Code Online (Sandbox Code Playgroud)

当您的可执行文件启动时,系统加载程序将解析此导入,因此您不必担心链接的详细信息.