DLL导出一个c++类,接口方法
Mature Approach(用抽象c++接口)
接口类:
MatureApproach.h
#pragma once #ifdef MATUREAPPROACH_EXPORTS #define MATUREAPPROACH_API __declspec(dllexport) #else #define MATUREAPPROACH_API __declspec(dllimport) #endif class IExport { public: virtual void Hi() = 0; virtual void Test() = 0; virtual void Release() = 0; }; extern "C" MATUREAPPROACH_API IExport* _stdcall CreateExportObj(); extern "C" MATUREAPPROACH_API void _stdcall DestroyExportObj(IExport* pExport);
MatureApproach.cpp
// MatureApproach.cpp : Defines the entry point for the DLL application. // #include "stdafx.h" #include "MatureApproach.h" #include "ExportClassImpl.h" #ifdef _MANAGED #pragma managed(push, off) #endif BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #ifdef _MANAGED #pragma managed(pop) #endif MATUREAPPROACH_API IExport* APIENTRY CreateExportObj() { return new ExportImpl; } //这里不能直接delete pExport,因为没有把IExport的析构函数定义为虚函数 MATUREAPPROACH_API void APIENTRY DestroyExportObj(IExport* pExport) { pExport->Release(); }
实现类:
#pragma once #include "MatureApproach.h" class ExportImpl : public IExport { public: virtual void Hi(); virtual void Test(); virtual void Release(); ~ExportImpl(); private: };
cpp略
配置要点:
最后导出MatureApproach.h,MatureApproach.dll,MatureApproach.lib
调用:
配置
包含MatureApproach.h目录
添加MatureApproach.lib目录
指定MatureApproach.lib
代码调用:
#include "MatureApproach.h" //#pragma comment(lib, "../debug/MatureApproach.lib") int _tmain(int argc, _TCHAR* argv[]) { IExport* pExport = CreateExportObj(); pExport->Hi(); pExport->Test(); DestroyExportObj(pExport); system("pause"); return 0; }
参考:
(40条消息) 【C++笔记 】如何从DLL中导出一个c++类_muyijames的博客-CSDN博客_c++ dll导出类