我用VS C++创建了一个dll(当然是一个dll项目),头文件的代码如下:
#pragma once
#include <iostream>
#include "..\..\profiles/ProfileInterface.h"
using namespace std;
extern "C" __declspec(dllexport) class CExportCoordinator: public CProfileInterface
{
public:
CExportCoordinator(void);
virtual ~CExportCoordinator(void);
CProfileInterface* Create();
void Initialize();
void Start();
};
这是 dll 的 .cpp 文件:
#include "StdAfx.h"
#include "ExportCoordinator.h"
CExportCoordinator::CExportCoordinator(void)
{
}
CExportCoordinator::~CExportCoordinator(void)
{
}
CProfileInterface* CExportCoordinator::Create(){
cout << "ExportCoordinator3 created..." << endl;
return new CExportCoordinator();
}
void CExportCoordinator::Initialize(){
cout << "ExportCoordinator3 initialized..." << endl;
}
void CExportCoordinator::Start(){
cout << "ExportCoordinator3 started..." << endl;
}
我导出了整个课程CExportCoordinator
,因为我需要使用它提供的所有三种方法。以下是来自主应用程序的代码,它在运行中加载上面给出的 dll。
typedef CProfileInterface* (WINAPI*Create)();
int _tmain(int argc, _TCHAR* argv[])
{
HMODULE hLib = LoadLibrary(name);
if(hLib==NULL) {
cout << "Unable to load library!" << endl;
return NULL;
}
char mod[MAXMODULE];
GetModuleFileName(hLib, (LPTSTR)mod, MAXMODULE);
cout << "Library loaded: " << mod << endl;
Create procAdd = (Create) GetProcAddress(hLib,"Create");
if (!procAdd){
cout << "function pointer not loaded";
}
return;
}
在输出中,我得到正确的库已加载,但该函数指针procAdd
为 NULL。我认为这与名称修饰有关,并extern "C"
在导出 dll 标头中的类时添加,但没有任何改变。顺便说一句,我用dll导出查看器查看了类的导出函数,整个类导出正确。有什么帮助吗?
更新
dll的头文件有错误。我不应该extern "C" __declspec(dllexport)
在上课前使用,因为那时课程根本不会被导出。如果我使用class __declspec(dllexport) CExportCoordinator
,则该类被正确导出,但无论如何我无法获得除 NULL 之外的函数地址。