I have written the following code (x64 VS 2015):
typedef void(__stdcall *foo)(void* v);
HMODULE hmod = GetModuleHandle(NULL);
foo f = (foo) GetProcAddress(hmod, "_foo0");
f(0);
foo0 is defined as:
extern "C" void __stdcall foo0(void* v){int a = 0;}
I have disabled all optimizations and security checks.
What I want the code to do is to find the address of the foo0 and then call it.
For some weird reason, calling GetLastError() after GetModuleHandle() returns 0x00000032 which means ERROR_NOT_SUPPORTED, but it does return some nonzero value which I assume is the handle to the executable. GetProcAddress() returns 0x0000000000000000 and a GetLastError() call after it returns 0x0000007f which means ERROR_PROC_NOT_FOUND, but I defined the proc!
Why is this happening? Is GetProcAddress() not supposed to be used with GetModuleHandle()?
The code fails because GetProcAddress requires the supplied symbol to have been exported from the module in question. That is, the symbol must have been listed in the PE module's export table. You do not export the symbol, and so GetProcAddress cannot find it. Hence GetProcAddress returns NULL. If you wish to use GetProcAddress then you must export the symbol. Either by naming it in a .def file, or by using __declspec(dllexport).
Some other comments:
You appear to have a mismatch of calling conventions, stdcall and cdecl.
You don't perform any error checking. For these particular function you need to check the return value. If that indicates that the function has failed, then call GetLastError for extended error information.
It should be:
extern "C" __declspec(dllexport) void foo0(void* v) { int a = 0; }
and:
foo f = (foo)GetProcAddress(hmod, "foo0");
^^~~~ no need for underline
as to your GetLastError issue, I am not sure about it - I suppose it might be some random value.
Related
I have a simple program that exports a DLL, this DLL exports functions from another DLL:
// SDK_DLL.cpp :
#include "functions.h"
#include "functions_advanced.h"
#include "stdafx.h"
#include <stdio.h>
using namespace std;
extern "C"
{
__declspec(dllexport) void DisplayHelloFromDLL()
{
printf("Hello from DLL...");
}
__declspec(dllexport) function_config FuncInit = appd_config_init();
__declspec(dllexport) function_config * FuncInit2()
{
function_config* cfg = function_config_init();
return cfg;
}
}
The function_config_init() returns a pointer, I cannot seem to find a way of making this proper export declaration.
I am loading a simple function to Delphi this way:
procedure DisplayHelloFromDLL; external 'C:\Users\Administrator\Documents\Visual Studio 2017\Projects\SDK_DLL\Debug\SDK_DLL.dll';
Will I need to change the way I am loading this pointer returning function?
Thanks a lot for your help.
FuncInit is an exported variable. Delphi does not support importing of variables via external, only of functions. If you need to import FuncInit, you will have to use GetProcAddress() directly to get a pointer to the variable at runtime:
type
// you did not show the C/C++ declaration
// of function_config, so I can't provide
// a translation here, but it is likely to
// be a struct, which is a record in Delphi ...
function_config = ...;
pfunction_config = ^function_config;
function GetFuncInit: pfunction_config;
begin
Result := pfunction_config(GetProcAddress(GetModuleHandle('SDK_DLL.dll'), 'FuncInit'));
end;
var
FuncInit: pfunction_config;
FuncInit := GetFuncInit;
For purposes of interop across languages/compilers, the only portable calling conventions are cdecl and stdcall. When no calling convention is specified in code, the default used by most C and C++ compilers is __cdecl (but can usually be specified in compiler settings), while the default used by Delphi is register instead (__fastcall in C++Builder).
When no parameters or return value are used, like in DisplayHelloFromDLL(), then declaring the wrong calling convention does not really matter. But when parameters and/or a return value are used, like in FuncInit2(), then declaring the correct calling convention matters. See Pitfalls of converting for more details.
So, the two DLL functions in question would likely need to be declared like the following in Delphi:
type
function_config = ...;
pfunction_config = ^function_config;
procedure DisplayHelloFromDLL; cdecl; external 'SDK_DLL.dll' name '_DisplayHelloFromDLL';
function FuncInit2: pfunction_config; cdecl; external 'SDK_DLL.dll' name '_FuncInit2';
If the DLL uses a .def file to remove name mangling from the exported names, you can omit the name attribute:
type
function_config = ...;
pfunction_config = ^function_config;
procedure DisplayHelloFromDLL; cdecl; external 'SDK_DLL.dll';
function FuncInit2: pfunction_config; cdecl; external 'SDK_DLL.dll';
I want to write a very, very small program that parses the launch arguments and chooses one of several DLLs to "boot into."
I've already written an application that I'd like to "run" as a DLL by writing it as an application, then changing the Visual Studio project properties to build it as a DLL instead. I know I need to use LoadLibrary and GetProcAddress in concert to get the functionality I want, but I'm having trouble finding clear and comprehensive documentation on this, as a lot of the use cases aren't really of this nature. Also, I have to go this route based on the project and platform restrictions.
I found this page, which has some information, but it's not clear enough for me to adapt for my purposes.
Edit: Here's where I'm at right now.
I have a DLL project whose main function signature looks something like this:
__declspec(dllexport) int cdecl main(int argc, char *argv[])
I also have an application project whose attempt at loading the DLL and running the above function looks like this:
typedef int (CALLBACK* LPFNDLLFUNC1)(int, char *);
...
HMODULE dllHandle = NULL;
BOOL freeResult, runTimeLinkSuccess = FALSE;
LPFNDLLFUNC1 lpfnDllFunc1; // Function pointer
if (args->IsEmpty())
{
dllHandle = LoadLibrary(L"TrueApplication.dll");
if (NULL != dllHandle)
{
lpfnDllFunc1 = (LPFNDLLFUNC1)GetProcAddress(dllHandle, "main");
if (lpfnDllFunc1)
{
int retVal = lpfnDllFunc1(0, "1");
}
Currently, the LoadLibrary call works, but not GetProcAddress.
First of all, changing project type from executable to DLL is not enough to make a DLL. You also need to export some symbols to create your API. At least, you need to decorate the functions you are exporting with __declspec(dllexport). However, I recommend that you export C API, meaning extern "C" functions with C-compatible arguments. So, the functions you export should be prepended with extern "C" __declspec(dllexport).
Once you have done that, you can dynamically load your DLL like this:
const char* dllname = "myfile.dll";
h = LoadLibrary(dllname);
if( h == nullptr )
{
/*handle error*/
}
using myfunc_type = bool (*)(int x, double y); //example
auto myfunc = reinterpret_cast<myfunc_type>(GetProcAddress(h, "myfunc"));
//......
myfunc(x,y); //call the imported function
This solution takes more work than static loading with /delayload shown by Jerry Coffin, but it has an advantage: if a DLL is required but not found, you can give users your own error message instead of relying on the message coming from Windows (which is often unacceptable for non-tech people). You can also include API version verification with its own custom error message in the API.
Edit: the code sample will work if you change it like this
extern "C" __declspec(dllexport) int main(int argc, char *argv[]){...}
typedef int (* LPFNDLLFUNC1)(int, char **);
You do not need GetProcAddress (...) to do this, though that approach (Option #2) is simpler once you understand how the compiler generates symbol names.
Option #1
DllMain Spawns a Main Thread
Never do anything complicated inside of DllMain, you may deadlock your software.
DLLs have their own entry-point (and exit-point and thread attach-point ... it's a really busy function). Just calling LoadLibrary (...) on your DLL causes at minimum one call to DllMain (...) for process attach.
BOOL
APIENTRY
DllMain ( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved )
You can actually treat ul_reason_for_call == DLL_PROCESS_ATTACH as a mandate to execute DllMain as if it were your program's main function.
Now, by no means should you actually start a program loop here... anytime DllMain runs it holds a very important operating system lock (DLL Loader) and you need to release that by returning for normal program operation.
That means if you want to use DllMain as your program's entry-point, it needs to spawn a thread and your original main method must not return until that thread finishes...
Option #2
DLL Exports a main Function.
Be very mindful of calling convention, the compiler will rename the symbols for you and make locating functions in a DLL with GetProcAddress less than intuitive.
In your DLL, export main:
__declspec (dllexport)
int
__cdecl main (int argc, char *argv [])
{
printf ("foobar");
return 0;
}
In your program, import main from the DLL:
// Need a typedef for the function you are going to get from the DLL
typedef int (__cdecl *main_pfn)(int argc, char *argv[]);
int main (int argc, char *argv[])
{
HMODULE hModMyDLL = LoadLibraryA ("MyDll.dll");
if (hModMyDLL != 0) {
//
// The preceding underscore deals with automatic decorations
// the compiler added to the __cdecl function name.
//
// It is possible to do away with this completely if you use a .def
// file to assign export names and ordinals manually, but then you
// lose the ability to tell a function's calling convention by its
// name alone.
//
main_pfn MyMain = (main_pfn)
GetProcAddress (hModMyDLL, "_main");
// Call the main function in your DLL and return when it does
if (MyMain != nullptr)
return MyMain (argc, argv);
}
return -1;
}
Both approaches have their merits.
Spawning a thread from DllMain avoids knowing anything at all about how the DLL you want to load is is implemented, but it also requires you to design your main function never to return -- the DLL will call ExitProcess (...).
Exporting functions and later importing them by name allows you to avoid pussyfooting around the Windows DLL loaderlock. However, if you do not use a .def file to explicitly name the exported symbols, the compiler is going to add decorations such as _... (__cdecl) or ...#n (__stdcall) to the names and you have to learn these conventions to do anything useful with GetProcAddress.
You don't have to use LoadLibrary and GetProcAddress to invoke the functionality in the DLL.
More often, you'd create your DLLs, each with its own entry point. For the moment, let's assume you want to parse the command line, choose a DLL, and invoke its entry point without arguments. You end up with something like this:
void DLL_a();
void DLL_b();
void DLL_c();
int main(int argc, char **argv) {
// we'll assume DLL_a is the default:
if (argc < 2)
DLL_a();
// For now, we'll do a *really* trivial version of parsing the command line
// to choose the right DLL:
if (argv[1][0] == 'A')
DLL_a();
else if (argv[1]][0] == 'B')
DLL_b();
else if (argv[1][0] == 'C')
DLL_c();
else {
std::cerr << "Unrecognized argument\n";
return 1;
}
}
When you link your main, you'll specify the .lib corresponding to each DLL, and you'll probably want to specify the /delayload flag to the linker. This means a DLL won't be loaded until a function in the DLL is actually invoked. If, for example, you want to distribute a reduced-functionality version of your program that only includes DLL A, it'll still be able run (without DLL B or C present on the user's system) as long as no function from DLL B or C is ever called. If you don't specify /delayload, the loader will attempt to map all the DLLs to RAM as the program starts up, run their DllMain to initialize them for use, do the same recursively for all the DLLs they depend on, etc.
/delayload has one other advantage: it avoids mapping the other DLLs to addresses at all if they're never used. It sounds like any given invocation will only use one DLL, so that's probably a win in your case.
This is my exported function in dll1
extern"C" __declspec(dllexport) int FUN1(char* p){
return p[0];
}
I am calling this FUN1 from other project.Below is the code
#include
#include
using namespace std;
typedef int (*MYFUN1)(char*);
int main()
{
HMODULE hMod = LoadLibrary ("C:\\Users\\admin\\Documents\\Visual Studio 2010\\Projects\\CalledFun\\Debug\\CalledFun.exe");
if(hMod != NULL)
{
MYFUN1 pCtor = (MYFUN1) GetProcAddress (hMod, "FUN1");
int a = pCtor("calling a value") ;
cout<<a;
}
}
If I remove the extern "C" from dll1 then that function address is returning as NULL when calling GetProcAddress in dll2. Since both are written in c++ I thought name mangling will not effect this.I thought if we use c and c++ libraries combinely then only we need to mention extern "C" ,Can anyone help me to get out of this confusion
Thanks in advance
You need to disable name mangling because you are using Windows API like LoadLibrary to which you provide function name. Windows API an LoadLibrary in particular know nothing about your compiler name mangling, so you need to turn it off.
code:
#include <cstdlib>
#include <iostream>
#include <windows.h>
using namespace std;
void calldll();
int main(int argc, char *argv[])
{
calldll();
system("PAUSE");
return EXIT_SUCCESS;
}
void calldll()
{
HINSTANCE LoadMe;
LoadMe = LoadLibrary("Trans_ATL.dll");
if(LoadMe!=0)
cout<<"loaded successfully\n";
else
cout<<"loading error\n";
/* get pointer to the functions in the dll*/
FARPROC function01 = GetProcAddress(LoadMe,"EnableLastCharTashkeel");
FARPROC function02 = GetProcAddress(LoadMe,"EnableEmphaticLAM_RAA");
FARPROC function03 = GetProcAddress(LoadMe,"SetText");
FARPROC function04 = GetProcAddress(LoadMe,"GetResult");
typedef void (__stdcall * pICFUNC01)(bool);
typedef void (__stdcall * pICFUNC02)(bool);
typedef bool (__stdcall * pICFUNC03)(string);
typedef string (__stdcall * pICFUNC04)(string);
pICFUNC01 EnableLastCharTashkeel_function;
EnableLastCharTashkeel_function = pICFUNC01(function01);
pICFUNC02 EnableEmphaticLAM_RAA_function;
EnableEmphaticLAM_RAA_function = pICFUNC02(function02);
pICFUNC03 SetText_function;
SetText_function = pICFUNC03(function03);
pICFUNC04 GetResult_function;
GetResult_function = pICFUNC04(function04);
EnableLastCharTashkeel_function(true);
EnableEmphaticLAM_RAA_function(true);
FreeLibrary(LoadMe);
}
in this code i call a dll it load successfully but when i try to use any function it compile without any errors but at the line
EnableLastCharTashkeel_function(true); (first call for a function)
it froozes and give me the following
Unhandled exception at 0x00000000 in test_trans_new.exe: 0xC0000005: Access violation reading location 0x00000000.
i guess that this becuse the function pointer point to NULL but i don't know how to fix it
i use visual c++ 2010
thanks in advance
thank you for all your replies which are realy helpfull but the problem still ocurrs but i approximately know the reason if i correct the problem is that the functions i try to access are of type COM so any idea about using this type
thanks in advance
FARPROC function01 = GetProcAddress(LoadMe,"EnableLastCharTashkeel");
That's a guaranteed NULL. Calling it does go kaboom, you didn't check if the function succeeded. The exported function is not named "EnableLastCharTashkeel". A more likely string is "?EnableLastCharTashkeel##YAX_N#Z". That's the name of the function after the C++ compiler mangled it, a trick to support overloaded functions.
You can declare the function extern "C", that suppresses name mangling and makes the function name "_EnableLastCharTashkeel". Note the leading underscore, used by the 32-bit compiler to mark that the function uses the __cdecl calling convention. To be sure, run Dumpbin.exe /exports on your DLL from the Visual Studio Command Prompt, it shows the exported names.
It's most likely 0 because the symbol you were trying to find in the DLL wasn't found, which would suggest that (a) it's either not there or (b) there might be a typo in the function name or (c) the function name might be mangled because it's being exported as a decorated name. This happens quite a lot in C++...
Unless the library exporting those four functions is under your control, use dumpbin /EXPORTS and have a look at the correct spelling of the symbols.
Hello guys: I've loaded my DLL in my project but whenever I use the GetProcAddress function. it returns NULL! what should I do?
I use this function ( double GetNumber(double x) ) in "MYDLL.dll"
Here is a code which I used:
typedef double (*LPGETNUMBER)(double Nbr);
HINSTANCE hDLL = NULL;
LPGETNUMBER lpGetNumber;
hDLL = LoadLibrary(L"MYDLL.DLL");
lpGetNumber = (LPGETNUMBER)GetProcAddress((HMODULE)hDLL, "GetNumber");
Checking return codes and calling GetLastError() will set you free. You should be checking return codes twice here. You are actually checking return codes zero times.
hDLL = LoadLibrary(L"MYDLL.DLL");
Check hDLL. Is it NULL? If so, call GetLastError() to find out why. It may be as simple as "File Not Found".
lpGetNumber = (LPGETNUMBER)GetProcAddress((HMODULE)hDLL, "GetNumber");
If lpGetNumber is NULL, call GetLastError(). It will tell you why the proc address could not be found. There are a few likely scenarios:
There is no exported function named GetNumber
There is an exported function named GetNumber, but it is not marked extern "c", resulting in name mangling.
hDLL isn't a valid library handle.
If it turns out to be #1 above, you need to export the functions by decorating the declaration with __declspec(dllexport) like this:
MyFile.h
__declspec(dllexport) int GetNumber();
If it turns out to be #2 above, you need to do this:
extern "C"
{
__declspec(dllexport) int GetNumber();
};
You might want to check if your GetNumber function is exported as an __stdcall function.
If so, try GetProcAddress(hDLL, "_GetNumber#N");, where N is the total number of bytes of GetNumber's argument list. For example, if your function signature is int GetNumber(int a, double b), its real name in DLL will be _GetNumber#12.
Reference: __stdcall
Most probably LoadLibrary() failed. You just can't see that because apparently you are not checking what it is returning:
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
EDIT:
We don't know how you are exporting the function on the DLL code, but this thread explains a couple of reasons on why GetProcAddress fails.