使用Delphi从调用C++dll
Call C++ dll from with Delphi
我的目标是从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文件来导出函数。
相关文章:
- 如何安全地从 DLL 调用返回对象
- C++结构到德尔福记录dll调用
- 从 C#-DLL 调用函数的 C++ 失败
- 可视C++:XGBoost 从 DLL 调用时不起作用
- Unity3D的OpenCV dll调用导致FPS下降
- 创建一个C++DLL以从C#DLL调用方法
- 从 dll 调用 opencv 垫到 Windows 表单,图像出现故障
- 努力使用 C# 从本机 DLL 调用该方法
- WinAPI - GetLastError 在通过 COM ATL DLL 调用时始终返回 0
- 必须使用C DLL调用C#.NET方法
- 如何直接从 pdfium.dll 调用 v8 函数
- 为什么从 DLL 调用类方法需要虚拟说明符?
- VBA 中的多个 DLL 调用
- 挂钩VirtualAlloc在系统DLL调用时返回NULLPTR
- 无法从 C DLL 调用该函数
- DLL 调用涉及 strncpy() 的方法
- JNA从DLL调用C++对象-java.lang.IollegalArgumentException:Structure
- 德尔福动态DLL调用中的奇怪行为
- 从非托管 DLL 调用 UWP api
- boost::从 DLL 调用时日志格式不起作用