0

我用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 之外的函数地址。

4

2 回答 2

1

在我看来,您应该将方法声明Createstatic方法并仅导出此方法。如果你愿意留下来NULLGetProcAddress你应该检查你的 DLL 的 Dependency Walker 导出(参见http://www.dependencywalker.com/)并将函数“Create”的名称修改为“_Create”或“_Create” @2"。

于 2010-08-18T10:17:43.813 回答
1
extern "C" __declspec(dllexport) class CExportCoordinator: public CProfileInterface 
{ 

这是无稽之谈。一个类不能是“extern C”

... inside the class ...
    CProfileInterface* Create();  

This creates a member function of the class, which is not probably what you want. For one thing, it will be mangled in the DLL, second, it will not be callable without the this pointer. Probably, you need this declaration:

extern "C" __declspec(dllexport) CProfileInterface* Create();  

and implemntation:

extern "C" __declspec(dllexport) CProfileInterface* Create(){
    cout << "ExportCoordinator3 created..." << endl;     
    return new CExportCoordinator();     
}   
于 2010-08-18T10:20:16.147 回答