用INDY9开发FTP客户端_03
-- BCB中创建与动态调用DLL的方法
Roger Yang
1. 创建DLL:
1. 根据DLL Wizard创建一个DLL的框架.
Source Type 选 C++
选中Use VCL 和 Multi Threaded
2. 由于用到sprintf,所以添加两个头文件
#include <stdio.h>
#include <stdlib.h>
3. 在文件的全局声明部分添加DLL接口函数的原形声明.
extern "C" __declspec(dllexport) int __stdcall dlltest(char *strTmp, long lTmp, int iTmp);
4. 同时对接口函数进行实现
int __stdcall dlltest(char *strTmp, long lTmp, int iTmp)
{
int iRtn;
char strDebugString[4096];
memset(strDebugString, 0, sizeof(strDebugString));
sprintf(strDebugString, "strTmp=[%s]", strTmp);
OutputDebugString(strDebugString);
memset(strDebugString, 0, sizeof(strDebugString));
sprintf(strDebugString, "lTmp=[%ld]", lTmp);
OutputDebugString(strDebugString);
memset(strDebugString, 0, sizeof(strDebugString));
sprintf(strDebugString, "iTmp=[%d]", iTmp);
OutputDebugString(strDebugString);
iRtn = iTmp + 1000;
return iRtn;
}
2. 动态调用DLL:
1. 将编译好的.DLL文件COPY到工程所在目录.
2. 头文件中声明类的私有成员
HINSTANCE dllInst;
int (__stdcall *dlltest)(char *, long, int); /* DLL接口函数的函数指针 */
3. 在按键事件中动态调用DLL的接口函数:
char strParam[4096];
long lParam = 1000;
int iParam = 2000;
int iRtn = 0;
OutputDebugString("Application Start");
dllInst = NULL;
/* 加载指定的DLL文件 */
dllInst = LoadLibrary("dlltest.dll");
if(dllInst == NULL)
{
ShowMessage("LoadLibrary [dlltest.dll] Failed!");
return;
}
/* 设置函数指针 */
dlltest = (int (__stdcall *)(char *, long, int))GetProcAddress(dllInst, "dlltest");
if(dlltest == NULL)
{
ShowMessage("Obtain Function Pointer Failed");
return;
}
strcpy(strParam, "这是 strParam 的值");
iRtn = dlltest(strParam, lParam, iParam);
ShowMessage("iRtn=["+(AnsiString)iRtn+"]");
return;
4. 在FormClose事件中释放资源:
if(dllInst != NULL)
{
FreeLibrary(dllInst);
}
3. 注意事项:
1. DLL接口函数对传入的参数要严格检查.
2. 调用DLL接口函数的函数指针之前要严格判断,指针是否为空.
3. 两边字符串的长度要统一.