Delphi動態呼叫C++寫的DLL
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++。