无法使用GetProcAddress获取dll函数的地址

时间:2010-08-18 09:49:42

标签: dll visual-c++-2005

我用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。我认为这与名称修改有关,并在dll的标题中导出类时添加了extern "C",但没有任何改变。顺便说一句,我使用dll export viewer来查看类的导出函数,并正确导出整个类。 有什么帮助吗?

更新
dll的头文件中有错误。我不应该在课前使用extern "C" __declspec(dllexport),因为那时类根本不会被导出。如果我使用class __declspec(dllexport) CExportCoordinator然后正确导出类,但无论如何我不能获得除NULL之外的函数的地址。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

extern "C" __declspec(dllexport) class CExportCoordinator: public CProfileInterface 
{ 

这是胡说八道。一堂课不能是“外部C”

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

这会创建一个类的成员函数,这可能不是你想要的。首先,它将在DLL中被破坏,其次,如果没有this指针,它将无法调用。可能你需要这个声明:

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

和实施:

extern "C" __declspec(dllexport) CProfileInterface* Create(){
    cout << "ExportCoordinator3 created..." << endl;     
    return new CExportCoordinator();     
}