本篇参考资料: <Professional C++, 4th Edition>
在上一章中, 已经粗略的介绍了 智能指针 unique_ptr
如果觉得本章的内容不适合你, 可以看 C++指针知识点目录
同时在 指针基础部分 中, 提到了指针是指向着一个地址, 但是我们很容易产生一个问题:
函数也有地址, 那么 指针能否指向函数?---- 当然可以
如果你是 信息学竞赛的, 没有必要了解(没有什么用处)
本篇是主要关于开发的, 现在步入正题
在讲这个之前, 了解一下: dll 文件
我们也会发现, 在许多windows应用程序目录中, 都存在这个东西
请点开上面的链接, 了解一下
看完之后, 我们可以知道, 所谓 dll, 就是 将某些函数或功能( 比如说类) 封装于此, 等着调用, 而这些东西的地址就存在这dll 中
我们不难想到, 只要我们找到其地址, 通过指针链接就可以了
由于内容超过了要讨论的范围, 只做简单的解释:
比如说编写一个返回 string 的 "Hello World!":
#ifndef _DLL_H_ #define _DLL_H_ #include <string> using std::string; #if BUILDING_DLL #define DLLIMPORT __declspec(dllexport) #else #define DLLIMPORT __declspec(dllimport) #endif //将该函数封装于 HelloWorld.dll中 extern "C" DLLIMPORT string HelloWorld() { return "Hello World!"; } #endif
cpp 中调用:
#include <windows.h> #include <iostream> #include <string> using namespace std; using HelloWorld=string(*)(void);//一个函数指针类型 int main() { HMODULE lib=::LoadLibrary("HelloWorld.dll");//加载dll HelloWorld func=(HelloWorld)::GetProcAddress(lib,"HelloWorld");//指向函数名"HelloWorld"的地址 cout<<func()<<endl; return 0; }
输出:
Hello World!
函数指针就讲到这里了, 关于指针的其他方面请看: C++指针目录