2010-08-18 56 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」的名稱。

相關問題