2014-02-28 44 views
1

我实现了一个简单的DLL项目在Visual Studio 2010.i两个数字都在DLL文件中实现附加功能,并已书面DEF文件导出添加功能。 其次,我已经创建使用Visual Studio 2010,其调用在上面,在不同位置的dll文件创建的附加功能的另一控制台应用程序。 问题是如何加载到.exe文件中的不同位置的此dll文件。如何加载.dll文件是在不同的位置以.exe

回答

1

我认为你需要使用LoadLibrary

HMODULE hmDLL = LoadLibrary(TEXT("path\\to\\your\\.dll")); 


您可能需要使用GetProcAddress找到你想从你的DLL调用的函数。

typedef YourFuncReturnType (*YourFuncPtr)(FunctionArgType1, FunctionArgType2); 
YourFuncPtr ptr = (YourFuncPtr)GetProcAddress(hmDLL, "YourFunctionName"); 
YourFunctionReturnType ret = ptr(arg1, arg2); 


FreeLibrary当你完成了它

FreeLibrary(hmDLL); 



比方说,我有一个DLL,并在DLL我有一个功能,美孚。


DLL.cpp

DLLEXPORT int Foo(int a, int b) 
{ 
    return a + b; 
} 



而且我还有一个项目,我想从我的DLL访问函数foo。

Program.cpp

#include <Windows.h> 
#include <iostream> 


// Define the pointer type for the function Foo 
typedef int (*funcptr)(int, int); 

char g_szDLLPath[] = "path\\to\\foo.dll"; 

int main() { 
    HMODULE hmDLL = LoadLibrary(g_szDLLPath); 

    if(NULL != hmDLL) { 
     funcptr fooPtr = (funcptr)GetProcAddress(hmDLL, "Foo"); 
     if(NULL != fooPtr) { 
      int result = fooPtr(5, 10); 

      if(result == 15) 
        std::cout << "Yay! Foo worked as expected!" << std::endl; 
       else 
        std::cout << "What the deuce! Foo returned " << result << std::endl; 

       result = fooPtr(10, 10); 

       if(result == 20) 
        std::cout << "Yay! Foo worked as expected!" << std::endl; 
       else 
        std::cout << "What the deuce! Foo returned " << result << std::endl; 
     } else { 
       perror("Error Locating Foo"); 
       return -1; 
     } 
    } else { 
     perror("Error Loading DLL"); 
     return -1; 
    } 
    return 0; 
} 
+1

正确的,这就是为什么简单的解决办法就是把旁边的EXE的DLL。 – MSalters

+0

@ MSalters同意。 –