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++。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值