我们就从新建工程开始:
(1)打开VS2010,文件->新建->项目,选择Win32项目
(2)工程名叫做“Win32Dll”,在点击确定后弹出的对话框中选择Dll这一项,并勾选导入符号选项,点击完成
这样一个创建Dll的工程就做好了,其实Dll的编写就是类的一种封装,格式完全可以按照C++中类的写法去完成,下面我改写了另一个老兄的例子:
1.在Win32Dll.h中的类CWin32Dll 里添加:
class WIN32DLL_API CWin32Dll { public: CWin32Dll(void); // TODO: 在此添加您的方法。 private: int m_nVar; std::string m_strVar; public: void set(int ); void printfValue(); void set_str(const std::string &); void printf_str(); }; extern WIN32DLL_API int nWin32Dll; //这里尤其要注意,当你想创建一个非成员函数时 WIN32DLL_API void printfValue(const int &); WIN32DLL_API int fnWin32Dll(void); |
2.以上类中尤其要注意非成员函数的的声明,之后便是在Win32Dll.cpp中的函数实现
CWin32Dll::CWin32Dll() { return; } void CWin32Dll::set(int v) { m_nVar = v; } void CWin32Dll::printfValue() { std::cout << m_nVar << std::endl; } void CWin32Dll::set_str(const std::string &str) { m_strVar = str; } void CWin32Dll::printf_str() { std::cout << m_strVar << std::endl; } void printfValue(const int &v) { std::cout << v << std::endl; } |
以上工作都做完后,进行编译链接,在工程Debug下就可以看到我们生成的.Dll文件和.lib文件