一种动态方式调用dll中类

IKPerson.h

#ifndef _IKPERSON_H_ #define _IKPERSON_H_ #ifdef DLL_EXPORT #define DLL_API extern "C" __declspec(dllexport) #else #define DLL_API extern "C" __declspec(dllimport) #endif /* 设计这个接口类的作用: 能采用动态调用方式使用这个类 */ class IKPerson { public: virtual ~IKPerson(void) //对于基类,显示定义虚析构函数是个好习惯(注意,为什么请google) { } virtual int GetOld(void) const = 0; virtual void SetOld(int nOld) = 0; virtual const char* GetName(void) const = 0; virtual void SetName(const char* szName) = 0; }; /* 导出函数声明 */ DLL_API IKPerson* _cdecl GetIKPerson(void); typedef IKPerson* (__cdecl *PFNGetIKPerson)(void); #endif

 

KChinese.h

#pragma once #define DLL_EXPORT #include "ikperson.h" class CKChinese : public IKPerson { public: CKChinese(void); ~CKChinese(void); virtual int GetOld(void) const; virtual void SetOld(int nOld); virtual const char* GetName(void) const; virtual void SetName(const char* szName); private: int m_nOld; char m_szName[64]; };

KChinese.cpp

#include "StdAfx.h" #include "KChinese.h" CKChinese::CKChinese(void) : m_nOld(0) { memset(m_szName, 0, 64); } CKChinese::~CKChinese(void) { } int CKChinese::GetOld(void) const { return m_nOld; } void CKChinese::SetOld(int nOld) { this->m_nOld = nOld; } const char* CKChinese::GetName(void) const { return m_szName; } void CKChinese::SetName(const char* szName) { strncpy(m_szName, szName, 64); } /* 导出函数定义 */ IKPerson* __cdecl GetIKPerson(void) { IKPerson* pIKPerson = new CKChinese(); return pIKPerson; }

 

调用代码

callclassExportDll.cpp

// callclassExportDll.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; #include "../../classExportDll/classExportDll/IKPerson.h" int _tmain(int argc, _TCHAR* argv[]) { HMODULE hDll = ::LoadLibrary(_T("classExportDll.dll")); if (NULL != hDll) { PFNGetIKPerson pFun = (PFNGetIKPerson)::GetProcAddress(hDll, "GetIKPerson"); if (NULL != pFun) { IKPerson* pIKPerson = (*pFun)(); if (NULL != pIKPerson) { pIKPerson->SetOld(103); pIKPerson->SetName("liyong"); cout << pIKPerson->GetOld() << endl; cout << pIKPerson->GetName() << endl; delete pIKPerson; } } ::FreeLibrary(hDll); } return 0; }

你可能感兴趣的:(c,api,Google,null,dll)