How to call exported function from dll in C/C++?

1

My aim is to call some function via its address. How can I do it?

I have done the next work for such aim, but at first(1) - I've got access violation ( don't know why ) and with the second I have some problems with calling function is ASM with ESP value...

The first (the problem with access violation):

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

const DWORD_PTR offset = 0x00001a90;

typedef void (__stdcall *uef)(int);

int main(void)
{
    HMODULE hModule = LoadLibrary(L"C:\\Windows\\system32\\OpenAL32.dll");

    DWORD_PTR addr = (DWORD_PTR)hModule + offset;

    uef func = (uef)offset;
    func(0);

    return 0;
}

The second (problems at runtime with ESP value):

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

typedef void (__stdcall *uef)(int);

int main(void)
{
    HMODULE hModule = LoadLibrary(L"C:\\Windows\\system32\\OpenAL32.dll");
    uef obj = NULL;

    if(hModule != NULL)
    {
        obj = reinterpret_cast<uef>(GetProcAddress(hModule, "alEnable"));
    }

    if(obj != NULL)
    {
        (*obj)(0);
    }

    if(hModule != NULL)
    {
        FreeLibrary(hModule);
    }

    return 0;
}

How could I solve this problem?

PS

And the another main question is:

How can I dynamically calculate the function address in runtime for next calling?

Thanks,

Best Regards!

function
dll
call
dllexport
function-address
asked on Stack Overflow Jun 10, 2012 by Secret • edited Jun 12, 2013 by Matt

1 Answer

1

First, there is a major issue (hence the access violation) with the hardcoded address offset (const DWORD_PTR offset = 0x00001a90). Don't do that! How can you know that the offsett will not be changed because of ASLR?

answered on Stack Overflow Jun 11, 2012 by mox

User contributions licensed under CC BY-SA 3.0