来源:http://blog.csdn.net/yysdsyl/article/details/2626033
动态dll的类导出:CPPDll2->test.h
#pragma once //#include "boost/shared_ptr.hpp" class Test { public: virtual ~Test() {} virtual void DoIt() =0; }; // extern "C" _declspec(dllexport) std::auto_ptr<Test> CreateTest(); // extern "C" _declspec(dllexport) boost::shared_ptr<Test> CreateTest(); extern "C" _declspec(dllexport) Test* CreateTestPtr(); extern "C" _declspec(dllexport) void DeleteTestPtr(Test*);
动态dll的类导出的实现:CPPDll2->test.cpp
//test.cpp #include "stdafx.h" #include "Test.h" #include <stdio.h> // #include <memory> // #include "boost/shared_ptr.hpp" class CTest : public Test { public: virtual void DoIt() { printf("Should do something/n"); } }; // std::auto_ptr<Test> CreateTest() // { // return std::auto_ptr<Test>(new CTest); // } // boost::shared_ptr<Test> CreateTest() // { // return boost::shared_ptr<Test>(new CTest); // } Test* CreateTestPtr() { return new CTest(); } void DeleteTestPtr(Test* t) { if(t !=NULL) { delete t; t =NULL; } }
对loadlibrary的分装,可以作为tools:
//library.h #pragma once #include <windows.h> #include <string> #include <assert.h> class Library { public: explicit Library(const wchar_t* name) { m_handle = LoadLibrary(name); assert(m_handle); if (!m_handle) throw std::runtime_error(std::string("Could not find library file:")); } ~Library() { FreeLibrary(m_handle); } void* GetProc(const char* name) { void* proc = ::GetProcAddress(m_handle, name); assert(proc); return proc; } private: HMODULE m_handle; };
client的调用:
#include "stdafx.h" #include "library.h" #include "../CppDll2/test.h" int _tmain(int argc, _TCHAR* argv[]) { typedef Test* (*CREATE)(); typedef void (*DEL)(Test*); Library lib(L"CppDll2.dll"); std::auto_ptr<Test> test = ((std::auto_ptr<Test> ) lib.GetProc("CreateTest")); Test* test = (((CREATE)(lib.GetProc("CreateTestPtr")))()); test->DoIt(); ((DEL)(lib.GetProc("DeleteTestPtr")))(test); return 0; }