Delphi XE 调用 C++ Builder XE 开发的DLL库

来源:互联网 发布:南昌大学教学网络平台 编辑:程序博客网 时间:2024/06/04 18:42

【首先用C++ Builder XE 制作DLL

步骤1FileNewOtherC++ Builder ProjectDynamic link Library,新建一个DLL工程。保存默认文件名File1.cDllEntry.c,保存工程文件名为myDLL.cbproj

步骤2FileNewUnit - C++Builder,新建一个C文件,保存为UMyDll.c

步骤3:向UMyDll.c添加代码如下:

//---------------------------------------------------------------------------

#pragma hdrstop

#include "UMyDll.h"

#include "Math.h"

//---------------------------------------------------------------------------

#pragma package(smart_init)

double dblValue(double);

double halfValue(double);

//extern "C" _export _stdcall double changeValue(double, bool);

double dblValue(double value)

 {

    return value * value * value * sin(2);

};

double halfValue(double value)

 {

    return value / 2.0;

}

double _export _stdcall changeValue(double value, bool whichOp) 

{

    return whichOp ? dblValue(value) : halfValue(value);

}

步骤4(可选):为防止在一个程序文件中多次包含头文件,可以将UMyDll.c中的extern "C" _export _stdcall double changeValue(double, bool);移入UMyDll.h中,如下:

原始UMyDll.h文件内容:

//---------------------------------------------------------------------------

#ifndef UmyDllH

#define UmyDllH

//---------------------------------------------------------------------------

#endif

移入extern "C" _export _stdcall double changeValue(double, bool);后的UMyDll.h文件内容:

//---------------------------------------------------------------------------

#ifndef UmyDllH

#define UmyDllH

//---------------------------------------------------------------------------

#ifdef __cplusplus

extern "C"

{

#endif

extern "C" _export _stdcall double changeValue(double, bool);

#ifdef __cplusplus

}

#endif

#endif

步骤5:编译生成Dll文件MyDll.dll

【在Delphi XE中调用生成的MyDll.dll

步骤1:新建一个Delphi工程,保存工程为MyTest.proj,保存单元文件为Unit1.pas,在Form1中添加两个按钮Button1Button2,一个文本框Edit1,修改Unit1.pas内容如下:

unit Unit1;

interface

uses

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

  Dialogs, StdCtrls;

type

  TForm1 = class(TForm)

    BtnAction: TButton;

    BtnClose: TButton;

    Edit1: TEdit;

    procedure BtnCloseClick(Sender: TObject);

    procedure BtnActionClick(Sender: TObject);

  private

    { Private declarations }

  public

    { Public declarations }

  end;

var

  Form1: TForm1;

implementation

{$R *.dfm}

function changeValue(x:Double;f:Boolean):Double;stdcall;external 'test.dll';

procedure TForm1.BtnActionClick(Sender: TObject);

begin

  Edit1.Text:=FloatToStr(changeValue(3,True));

end;

procedure TForm1.BtnCloseClick(Sender: TObject);

begin

  Close;

end;

end.

步骤2编译、运行,如下图。


原创粉丝点击