AcarX
AcarX

Reputation: 281

DLL swapping in c, am I doing it wrong?

So I would like to be able to change the behaviour of my application during runtime without using any external scripting languages. In order to achive that I tried using DLLs. I have something like:

begin program;
load dll and function pointers;
init_func_ptr();
loop:
    if(compiled_new_version)
    {
        pause threads;
        unload dll;
        overwrite expired dll with new dll;
        load dll and function pointers;
        resume threads;
    }
    update_func_ptr(state);

Initially I didn't have any problems. However once I wrote some actual code I started crashing after reloading the dll. Only function pointers that I'm exporting/reloading manually are 'init' and update'.

Some information about the crashes I'm having. It's crashing in the middle of nowhere, there're bunch of entries in the callstack with the address '0xCDCDCDCD'(worth to mention that this happens when I'm using Visual Studio as the debugger and the application is compiled in debug mode).

What I believe happening is, when I pause the threads, one or more of them are executing some code within the expired dll so when I unload that dll and resume the threads they're causing the crash.

How can I solve this problem?

Upvotes: 0

Views: 177

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

You may need to write code in your DLL to check whether it is safe to unload the DLL. For example, every function upon entry increments a DLL global variable and decrements it upon exit. Only when it is zero can the DLL be safely unloaded.

You may also need to write code that manages that the DLL is in "shutdown mode" and should no longer be called. For example a wrapper module with wrappers for all exported functions that can pause the calling thread until the DLL is reloaded. Note that this module probably cannot be in the DLL itself.

I suggest you first make a skeleton application for testing the concept that contains the minimal functions for counting, synchronization and loading.

Upvotes: 2

Related Questions