2010-08-18 36 views
0

获得DLL函数的地址,我创建了一个DLL与VS C++(当然作为一个dll项目)与头文件的下面的代码:不能GetProcAddress的

#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(); 
}; 

这里是.cpp文件的dll:

#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查看类的导出函数,并且整个类都正确导出。 有什么帮助吗?

UPDATE
dll的头文件中有错误。我不应该在课前使用extern "C" __declspec(dllexport),因为那样课程根本不会被导出。如果我使用class __declspec(dllexport) CExportCoordinator,那么该类将正确导出,但无论如何,我无法获得NULL以外的函数地址。

回答

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

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

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

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

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

和implemntation:

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

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