2012-11-24 59 views
0

我需要從託管的C++代碼動態加載.dll。 下面的代碼執行此在Windows下的dll

[DllImport("kernel32.dll", SetLastError = true, 
     CharSet = CharSet::Unicode, ExactSpelling = true, 
     CallingConvention = CallingConvention::StdCall)] 
    static HMODULE LoadLibrary(LPCTSTR lpFileName); 

    [DllImport("kernel32.dll", SetLastError = true, 
     CharSet = CharSet::Unicode, ExactSpelling = true, 
     CallingConvention = CallingConvention::StdCall)] 
    static BOOL FreeLibrary(HMODULE hModule); 

    [DllImport("kernel32.dll", SetLastError = true, 
     CharSet = CharSet::Unicode, ExactSpelling = true, 
     CallingConvention = CallingConvention::StdCall)] 
    static FARPROC GetProcAddress(HMODULE hModule, LPCSTR lpProcName); 

    typedef int (*CFunction)(); 

    int _tmain() 
    { 
     HMODULE pLib = LoadLibrary(TEXT("FunctionDLL.dll")); 
     if(pLib != 0) 
     { 
      FARPROC function = GetProcAddress(pLib, "QFunction"); 
      if (function != 0) 
       MessageBox::Show(Convert::ToString(function())); 

      FreeLibrary(pLib); 
     } 
     else 
     { 
      MessageBox::Show(L"Error", L"Couldn't load ell"); 
      Close(); 
     } 

     return 0; 
    } 

但功能一直是空的。我認爲,我們錯了。下面的DLL的代碼:

.h文件中

#ifdef __FUNCTIONDLL__ 
#define __FUNCTIONDLL__ 

#ifdef FUNCTIONDLL_EXPORTS 
    #define FUNCTIONDLL_API __declspec(dllexport) 
#else 
    #define FUNCTIONDLL_API __declspec(dllimport) 
#endif 

#ifdef __cplusplus 
extern "C" 
{ 
#endif 

FUNCTIONDLL_API int QFunction(); 

#ifdef __cplusplus 
} 
#endif // __cplusplus 

#endif // __FUNCTIONDLL__ 

.cpp文件

#include "FunctionDLL.h" 

int QFunction() 
{ 
    return 42; 
} 

回答

0

你有你的C++項目.DEF?如果不只是增加一個.DEF與

LIBRARY FunctionDLL 
EXPORTS 
    QFunction @1 
+0

我只是讓使用#ifdef來印刷錯誤,需要的#ifndef –

+0

這#IFDEF你錯過 – Ibrahim