使用Delphi从调用C++dll

Call C++ dll from with Delphi

本文关键字:C++dll 调用 Delphi 使用      更新时间:2023-10-16

我的目标是从Delphi(RAD Studio XE6)中调用用C++编写的函数(带有C接口)。最终,dll将由Visual Studio 2013生成,但我尝试从RAD Studio XE6生成dll开始。

因此,我在RadStudio中创建了一个Dll项目(使用VC++风格的Dll)。文件在这里

#include <vcl.h>
#include <windows.h>
#pragma hdrstop
#pragma argsused
int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved)
{
    return 1;
}
extern "C" int next(int n) {
    return n + 1;
}

它编译为Dll。在Delphi方面,代码如下:

program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
  System.SysUtils, Windows;
function next(a: Int32): Int32; cdecl;
  external 'Project3.dll';
var
  a: Int32;
begin
  try
    a := 3;
    Writeln('Hello world!', next(a));
    sleep(3000);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

该项目确实进行了编译,但没有运行。它给出以下错误:

*** A stack buffer overrun occurred in "C:...DebugProject1.exe"

它在以下装配线上出现故障

mov eax,[edi]

我已尝试将cdecl更改为std调用、pascal或register。但什么都不管用。

解决方案:多亏了Rudy,以下代码确实有效。首先是C++方面:

#include <vcl.h>
#include <windows.h>
#pragma hdrstop
#pragma argsused
int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved)
{
    return 1;
}
extern "C" __declspec(dllexport) int __stdcall next(int n) {
    return n + 1;
}

然后是德尔福方面。

program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
  System.SysUtils, Windows;
function next(a: Int32): Int32; stdcall;
  external 'Project3.dll';
var
  a: Int32;
begin
  try
    a := 3;
    Writeln('Hello world!', next(a));
    sleep(3000);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

您没有导出函数。这样做:

extern "C" 
{
    __declspec(dllexport) int next(int n)
    {
        return n + 1;
    }
}

使用extern "C"__declspec(dllexport)__cdecl的默认调用约定将倾向于导出的未修饰的函数。任何其他选择都会带来装饰。

在Delphi方面,它是:

function next(a: Integer): Integer; cdecl;
  external '...';

修饰并不是一件坏事,但如果你想使用stdcall并避免修饰,那么你应该使用.def文件来导出函数。