今天写了一个很简单的动态链接库:
“lib.h”
#ifndef LIB_H
#define LIB_H
extern "C" int _declspec(dllexport)add(int x,int y);
#endif
“lib.cpp”
#include"lib.h"
int add(int x,int y)
{
return x+y;
}
下面是一个测试程序:
“calldll.cpp”
#include<stdio.h>
#include <tchar.h>//宏 _T" "定义在此文件中
#include<windows.h>
typedef int (*lpAddFun)(int ,int );
int __cdecl main(int argc ,char*argv[])
{
HINSTANCE hdll;
lpAddFun addFun;
hdll=LoadLibrary(_T("..//debug//mydll.dll"));//此处字符串一定要用_T" "括起来
if(hdll!=NULL)
{
addFun=(lpAddFun)GetProcAddress(hdll,"add");
if(addFun!=NULL)
{
int result=addFun(2,4);
printf("2+4=%d ",result);
}
FreeLibrary(hdll);
}
return 0;
}
出现的问题:
开始时 在vc6.0中编译出现了这样的问题:
"error C2440: '=' : cannot convert from 'int (__stdcall *)(void)' to 'int (__cdecl *)(int,int)'
This conversion requires a reinterpret_cast, a C-style cast or function-style cast"
出错的语句为:addFun=GetProcAddress(hdll,"add");加上强制类型转换后此问题就解决了,如:"addFun=(lpAddFun)GetProcAddress(hdll,"add")"
然而在vs2005上又出现了其他问题:
首先是编译时”error C2664: 'LoadLibraryW' : cannot convert parameter 1 from 'const char [19]' to 'LPCWSTR' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast“
这个问题通过把hdll=LoadLibrary("..//debug//mydll.dll");中的字符用_T" "括起来就解决了。如:hdll=LoadLibrary(_T("..//debug//mydll.dll"));但还要#include <tchar.h>//宏 _T" "定义在此文件中
但接下来运行时又出现了问题:"没有找到 MSVCR80D.dll,因此这个程序未能启动,重新安装应用程序,可能会修复此问题" 解决这个问题花了不少时间最后将项目的配置属性改为Use MFC in a Shared DLL才把这个问题解决掉。