一.建立dll
菜单File --> New -->Other,弹出New Items 窗体,选择New页的DLL Wizard,点击OK.
弹出DLL Wizard窗体,默认选项即可(C++选中,Use VCL选中,Multi Threaded为灰色不可用)
点击OK.
在代码窗体中输入如下内容:
#include <vcl.h>
#include <windows.h>
#pragma hdrstop
#pragma argsused
//dll函数的外部接口
//int 函数的返回值 zhuanHuan(int) 为函数名和函数的参数
extern "C" __declspec(dllexport) int __stdcall zhuanHuan(int);
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, LPVOID lpvReserved)
{
return 1;
}
//dll函数的实现--把a的值加1,然后返回
int __stdcall zhuanHuan(int a)
{
int b;
b=a+1;
return b;
}
文件保存后,按F9编译即可.编译后,目录下产生一个Project1.dll文件.
二.应用dll
建立一个应用程序,在窗体上1个Button,2个Edit控件.
要实现在Edit1里输入一个数字,点击button按钮,调用dll的函数后,将返回值返回到Edit2控件中.
首先保存项目,之后把上面编译后的Project1.dll拷贝到现在的目录.
双击button1控件,在代码窗体中输入如下代码:
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int i = StrToInt(Edit1->Text);
HINSTANCE ins;
ins = LoadLibrary("Project1.dll");
if (ins==NULL)
{
throw "Can't load library!";
}
else
{
typedef __stdcall(*pZhuanHuan)(int); //定义数据类型
pZhuanHuan zhuanHuan;
zhuanHuan=(pZhuanHuan) GetProcAddress(ins,"zhuanHuan");
if (zhuanHuan==NULL)
{
FreeLibrary(ins);
throw "Can't Load Address!";
}
else
{
Edit2->Text = zhuanHuan(i);
}
}
if (!FreeLibrary(ins))
{
throw "Can't Free!";
}
}
//---------------------------------------------------------------------------
运行即可!