您的位置:首页 > 编程语言 > Delphi

Delphi动态调用C++写的DLL

2016-04-13 16:51 218 查看
c++ DLL 文件,建议用最简单的c++编辑工具。不会加入很多无关的DLL文件。本人用codeblocks+mingw。不像

VS2010,DLL编译成功,调用的时候会提示缺其他DLL。 系统生成的main.h和main.cpp

#ifndef __MAIN_H__

#define __MAIN_H__

#include <windows.h>

/* To use this exported function of dll, include this header

* in your project.

*/

#ifdef BUILD_DLL

#define DLL_EXPORT __declspec(dllexport)

#else

#define DLL_EXPORT __declspec(dllimport)

#endif

#ifdef __cplusplus

extern "C"

{

#endif

int DLL_EXPORT Add(int plus1, int plus2); //导出函数Add

#ifdef __cplusplus

}

#endif

#endif // __MAIN_H__

#include "main.h"

// a sample exported function

int DLL_EXPORT Add(int plus1, int plus2) //导出函数Add 的实现

{

int add_result = plus1 + plus2;

return add_result;

}

extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)

{

switch (fdwReason)

{

case DLL_PROCESS_ATTACH:

// attach to process

// return FALSE to fail DLL load

break;

case DLL_PROCESS_DETACH:

// detach from process

break;

case DLL_THREAD_ATTACH:

// attach to thread

break;

case DLL_THREAD_DETACH:

// detach from thread

break;

}

return TRUE; // succesful

}

只有一个简单函数Add,就是为了测试delphi能不能成功调用

delphi 用按钮加入调用函数

unit Unit1;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, StdCtrls;

type

TForm1 = class(TForm)

btn1: TButton;

Edit1: TEdit;

procedure btn1Click(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

var

Form1: TForm1;

_DLLMoudle: THandle;

_GetAdd:function (plus1:Integer; plus2:Integer):Integer;cdecl;

//动态调用,不要少了cdecl,百度看到是因为dll调用函数,传参数的差异

// function Add( plus1:Integer; plus2:Integer):Integer;

// stdcall; external 'MyDll.dll' name 'Add';

// 静态调用,静态调用有问题,还是声明stdcall 再C++种声明导出函数的原因

// 把stdcall 改为cdecl 就可以用静态调用了。具体C++声明函数和delphi对应关系看后面

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);

var

l_int : integer;

begin

try

_DLLMoudle := Loadlibrary('MyDLL.dll');

ShowMessage('加载成功!!!');

except

ShowMessage('加载失败!!!');

Exit;

end;

if _DLLMoudle > 32 then

begin

try

begin

@_GetAdd:=GetProcAddress(_DLLMoudle,'Add');

l_int:=_GetAdd(5,6);

Edit1.Text:=IntToStr(l_int);

end

except

ShowMessage('有问题!');

end;

end;

// l_int:=Add(1,3);

// Edit1.Text:=IntToStr(l_int);

end;

end.

C++的参数调用方式 对应的DELPHI的参数调用方式

_declspec cdecl

WINAPI,CALLBACK stdcall

PASCAL pascal

以上请多试一下。我也是测试很多次才成功的。以后核心逻辑用C++。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: