问题
I have got MyDll.dll and its function defined as below
void pascal Myfunction(BOOL);
when I'm trying to use the function in another project i am unable get the address of the function with GetProcAddress()
. Here is my code:
void callMyDll()
{
HINSTANCE hDll;
hDll=LoadLibrary(_T("MyDll.dll");
if(hDll!=NULL)
{
cout<<"\n DLL Loaded \n";
}
else
cout<<"\n DLL Not loaded\n"
typedef void (__stdcall *MyFunction)(bool)
Myfunction mf1 = (MyFunction) GetProcAddress(hDll, "MyFunction");
if (mf1!=NULL)
cout<<"\n Function Loaded Successfully \n";
else
cout<<"\n Function not loaded \n";
FreeLibrary(hDll);
}
I'm getting output as:
DLL Loaded
Function not loaded
But when I'm trying with known DLLs like glut32.dll and its functions it is working fine.
I think it may be problem with its function like
void pascal MyFunction(BOOL);
Can anybody help me in this regard?
回答1:
You need to use extern "C"
to prevent name mangling and ensure the function is exported:
extern "C" __declspec(dllexport) void Myfunction(BOOL);
To view the exports from your DLL you can use dumpbin.exe
utility that is shipped with Visual Studio:
dumpbin.exe /EXPORTS MyDll.dll
This will list the names of all exported symbols.
In addition to this do not have either of the following compiler switches specified:
Gz __stdcall calling convention: "Myfunction" would be exported as Myfunction@4
Gr __fastcall caling convention: "Myfunction" would be exported as @Myfunction@4
Note: I think last symbol is dependent on compiler version but is still not just "Myfunction".
回答2:
The DLL export process is subject to name mangling and decoration. The long obsolete 16 bit pascal
calling convention is equivalent to stdcall
on 32 bit platforms.
First of all you should use extern "C"
to specify C linkage and disable name mangling.
However, your function will still be subject to name decoration. If you export it with __declspec(dllexport)
then it will in fact be exported with the name _Myfunction@4
. If you wish to export it by its true name then you need to use a .def file.
However, the possibility still remains that you did not export the function from the DLL at all. Use Dependency Walker to check whether it was exported, and if so by what name.
回答3:
Why are you using the pascal
calling-convention? Perhaps that alters the names of symbols, and if so you might need to take that into account.
回答4:
The symbol is going to be decorated, so it will never be called MyFunction
, its more likely _MyFunction@4
. you can quickly check this using something like dumpbin.
You can read up more on mangling here, if you want to avoid mangling, you need to use a def
file to specify symbol names (or ordinals).
来源:https://stackoverflow.com/questions/9001619/regarding-getprocaddress