2012-04-20 74 views
2

我有以下代码:GetProcAddress函数 - 返回NULL

//mydll.cpp 
    #include <Windows.h> 
    #include <io.h> 

    #define STDOUT_FILEDESC 1 

    class MYSTDOUT { 
     bool shouldClose; 
     bool isBuffered; 
    public: 
     MYSTDOUT(bool buf = true, bool cl = true) 
      : isBuffered(buf), 
       shouldClose(cl) 
     {} 
     ~MYSTDOUT() { 
      if (shouldClose) { 
       close(STDOUT_FILEDESC); 
      } 
     } 
    }; 

    __declspec(dllexport) void* mydll_init_stdout() 
    { 
     static MYSTDOUT outs; 
     return &outs; 
    } 
//test_dll.cpp 
#include <stdio.h> 
#include <stdlib.h> 
#include <Windows.h> 
#include <io.h> 


typedef void* (__cdecl *MYPROC)(void); 


int main(void) 
{ 
    int fd; 
    void *pstdout; 

    MYPROC init_stdout; 
    HMODULE handle = LoadLibrary(TEXT("mydll.dll")); 

    init_stdout = (MYPROC)GetProcAddress(handle,"mydll_init_stdout");//NULL 

    FreeLibrary((HMODULE) handle); 
    return 0; 
} 

我得到init_stdout是NULL.What可能是一个问题吗? 手柄OK(NOT NULL) 谢谢

回答

7

这是由于名称的问题。

你需要用导出功能extern "C"为:

extern "C" 
{ 
    __declspec(dllexport) void* mydll_init_stdout() 
    { 
     static MYSTDOUT outs; 
     return &outs; 
    } 
} 
9

有一个支票的Dependency Walker,或dumpbin /exports,你会看到mydll_init_stdout已出口了错位的C++名称。这就是为什么GetProcAddress呼叫失败。

使用extern "C"可以防止损坏。

extern "C" 
{ 
    __declspec(dllexport) void* mydll_init_stdout() 
    { 
     static MYSTDOUT outs; 
     return &outs; 
    } 
}