Handmade Hero»Forums»Code
6 posts
Calling function from dll read access violation
Edited by kurorah on Reason: Initial post
So calling my game.UpdateAndRender() won't compile but will using (*game.UpdateAndRender)()
This however creates
1
UpdateAndRender was 0xFFFFFFFFFFFFFFFF
on Line 43 of below.

I'm trying to accomplish this without using #define macros.
Any ideas or help would be much appreciated.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
typedef void (*UpdateAndRender_t)();

struct win32_dll_code {
    bool32 valid;
    HMODULE DLL;
    UpdateAndRender_t *UpdateAndRender;
};

static struct win32_dll_code
Win32LoadCode(wchar *src_file)
{
    struct win32_dll_code res = {0};
    res.DLL = LoadLibraryW(src_file);
    if (res.DLL) {
        res.UpdateAndRender = (UpdateAndRender_t *)
            GetProcAddress(res.DLL, "UpdateAndRender");
        if (res.UpdateAndRender)
            res.valid = TRUE;
    }
    if (!res.valid)
        res.UpdateAndRender = 0;
        
    return res;
}

// ...

int WINAPI
WinMain(HINSTANCE hInstance,
        HINSTANCE hPrevInstance,
        LPSTR pCmdLine,
        int nCmdShow)
{
    struct win32_dll_code game = Win32LoadCode(L"game.dll");

    HWND wnd_handle = Win32CreateWindow(hInstance);
    if (!wnd_handle) return -1;

    while (Running) {
        ProcessMessages();

        if (game.valid)
            (*game.UpdateAndRender)(); // Crash is here
    }

    return 0;
}


The function UpdateAndRender is shown as been exported by dumpbin and is just a quick test:
1
2
3
4
void UpdateAndRender()
{
// Lots of output debugs not being triggered
}
Mārtiņš Možeiko
2559 posts / 2 projects
Calling function from dll read access violation
You have too many pointers there.

typedef void UpdateAndRender_t(); - this is function type
You use it like this: "UpdateAndRender_t *UpdateAndRender;" - this creates UpdateAndRender that is pointer to function.

If you have this:
typedef void (*UpdateAndRender_t)(); - that is already pointer to function.
Then doing "UpdateAndRender_t *UpdateAndRender;" - means you are creating pointer to pointer to function.

I suggest you to do only this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// create function type
typedef void UpdateAndRender_t(); 

// inside win32_dll_code create member that is pointer to function
UpdateAndRender_t* UpdateAndRender;

// to assign pointer just do regular cast:
res.UpdateAndRender = (UpdateAndRender_t*) GetProcAddress(res.DLL, "UpdateAndRender");

// and to call it, the dereferencing is optional in C
game.UpdateAndRender();