First, I create a simple dll called SimpleDll.dll
, its head file:
// SimpleDll.h
#ifdef MYLIBAPI
#else
#define MYLIBAPI __declspec(dllimport)
#endif
MYLIBAPI int Add(int a. int b);
its source code:
// SimpleDll.c
#include <windows.h>
#define MYLIBAPI __declspec(dllexport)
#include "SimpleDll.h"
int Add(int a, int b)
{
return a + b;
}
Then I call it in another project, and it works fine:
// TestSimpleDll.c
#include "stdafx.h"
#include <windows.h>
#include "SimpleDll.h"
#pragma comment(lib, "SimpleDll.lib")
int _tmain(int argc, _TCHAR* argv[])
{
printf("%d", Add(10, 30)); // Give the expected result 40
return 0;
}
开发者_JS百科
However, when I call GetProcAddress
to get it's address, it doesn't work!
// TestSimpleDll2.c
#include "stdafx.h"
#include <windows.h>
#include "SimpleDll.h"
#pragma comment(lib, "SimpleDll.lib")
int _tmain(int argc, _TCHAR* argv[])
{
printf("%d", Add(10, 30)); // Give the expected result 40
HMODULE hModule = GetModuleHandleA("SimpleDll.dll"); // hModule is found
PROC add_proc = GetProcAddress(hModule, "Add"); // but Add is not found !
// add_proc is NULL!
return 0;
}
Thanks for your help. (PS: I use VS2010 on Windows7)
Update: This is what the depedency walker show for theSimpleDll.dll
file:
You should use a .def file if you want to export the name for GetProcAddress. Otherwise you will have to deal with c++ name mangling and with symbol decorations.
You can avoid mangling by declaring your function as extern "C"
, but the only way to avoid decorations is to use a .DEF file.
One more thing - in Dependency walker - use F10 to toggle between decorated and undecorated names.
Dependency Walker is an excellent tool for troubleshooting DLL issues like this.
I'm assuming you are compiling the DLL as C code. Otherwise, C++ performs name mangling that would cause problems.
To avoid name mangling simply wrap the export definition in extern "C".
extern "C" {
MYLIBAPI int Add(int a. int b);
}
精彩评论