Hello,

I'm trying to approach .dll's. Tried some tutorials and got into 2 problems:
1. Using rundll32 from the command line is not working as expected. I write in cmd: "rundll32 mydll.dll MsgBox -32". It shows the MessageBox with text "15991798", changing every time I run it.
2. Calling a dll function from another program gives an error and closes: "dllUser.exe has stopped working. A problem caused the program to stop working correctly. Please close the program.". In console: "Process returned -1073741819 (0xC0000005) execution time : 70.894 s
Press any key to continue."

now here is my dll function:

extern "C" int DLL_EXPORT MsgBox(int someValue)
{
    //cout << "Value is : " << someValue << endl;
    string intStr;
    stringstream ss; //
    ss << someValue;
    intStr=ss.str();

    MessageBox(0, std::string(intStr).c_str() , "DLL Message", MB_OK | MB_ICONINFORMATION);

    return someValue;
}

and this is how I call it from dllUser.exe:

#include <iostream>
#include <windows.h>

using namespace std;

typedef int (*MsgFunction)(int);

HINSTANCE hinstDLL;

int main()
{
    MsgFunction MsgBox(0);
    hinstDLL = LoadLibrary("MyDLL.dll");
    if(hinstDLL!=0)
    {
        MsgBox=(MsgFunction)GetProcAddress(hinstDLL,"MsgFunction");
    }
    if(hinstDLL==0) cout << "NULL MsgBox\n";
    int x=MsgBox(5);
    if(x==5)
    {
        cout << "Message!!\n";
    }

    string s="Works!";
    MessageBoxA(NULL, s.c_str(),"Title",MB_OK);
    FreeLibrary(hinstDLL);
    return 0;
}

I may miss something here, so please bring some light in my head :)

When using rundll32. Read the description of this function, if you pass extra parameters on the command line of rundll32 then it passes a pointer to the parameters to the function it is calling.

That means a function called with parameters through rundll32 must take a const char * as its parameter type. Your function takes and int so what is actually being printed in the message box is the value of the pointer to this parameter which is also why it is different every time.

In your own code look at where you call GetProcAddress you have the function name wrong so a NULL pointer is almost certainly being returned. Since you then use the pointer without first checking that it is valid you are getting getting a memory access violation (because you are not allowed to dereference the NULL pointer.

OK... now I feel stupid :|
The problem was the function name in GetProcAddress..
The rundll32 passsing a const char* parameter I didn't know.. my bad.
Thanks for helping me! Small things makes big difference...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.