Secret
Secret

Reputation: 2647

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

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!

Upvotes: 1

Views: 2217

Answers (1)

mox
mox

Reputation: 6314

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?

Upvotes: 1

Related Questions