在函数前标注:extern "C" _declspec(dllexport)的函数才能被其他的程序通过dll的方式调用
例如:
extern "C" _declspec(dllexport) int add(int i1,int i2)
{
return i1+i2;
}
注意:需要把编译后生成的.dll和.lib文件拷贝到调用她的工程文件下。
动态链接库的链接方式:
1)静态链接:
声明:
#pragma comment(lib, "dll1.lib")
extern "C" _declspec(dllexport) int add(int i1,int i2);
2)动态链接:
typedef int( __cdecl* FunctionAdd)(int,int);//定义一个指向其所调用的函数的指针的类型,通过指针去调用函数。
HMODULE hModule;//定义一个动态链接库的句柄
FunctionAdd add;//定义函数指针
hModule = LoadLibrary("dlltest1.dll");
if(NULL == hModule)
{
//write handle about error code here!
}
add = (FunctionAdd)GetProcAddress(hModule,"add");//让add指针指向所调用函数
if(NULL == add)
{
//write handle about error code here!
}
//write code here!
FreeLibrary(hModule);//释放动态链接库
静态链接和动态链接的区别:静态链接在程序启动的时候就会去检查dll是否存在,如果不存在在启动的时候就会报错,程序无法启动;动态链接是在运行到的时候才会去检查是否存在,而且可以由程序员决定在dll不存在的时候判断逻辑。