0

I'm making a game engine, I've done a c++ hot reload for the scripting and I have one problem. The problem is that if the user makes a mistake and the script crashes, it will crash the engine as well. There are 2 projects, the first one that is an exe (the engine) and the other that is a dll that the user can modify and add whatever he wants for the scripting.

It is posible to catch an error in a dll function in order that my engine does not crash too?

Something like this:

auto item = current_scripts.begin();
for (; item != current_scripts.end(); ++item) {
    if (*item != nullptr) {
            try {
                // I would like to be able to catch all possible errors/exceptions the user might do
                throw (*item)->Update();  
                // this is calling a dll function that the exe does not know what is doing
            }
            catch(...) {
                LOG("Error In Update");
            }
        }
    }

1 Answers1

1

It is posible to catch an error in a dll function in order that my engine does not crash too?

This depends on how the DLL is made, and what sort of API you're using.

Normally, you should declare the DLL functions in an extern "C" block, which forces the functions to be exported in a C-style API. C does not have any built-in concept for exceptions and try/catch, so you have to build your own error handling inside the DLL and raise errors outside the DLL in a C-compatible way.

If you don't use extern "C" to wrap your DLL API, then it is considered a C++ API. These are very tricky to do right, and std::exception can only be caught outside the DLL if the exact same C++ runtime is being linked for the EXE & DLL.
If that is not the case, you must again catch the exceptions inside the DLL and raise errors outside the DLL in a C-compatible way.

Lastly, DLLs built with managed C++ or C# allow you to catch exceptions outside the DLL. This functionality is provided by the Common Language Runtime.


I would suggest that you consider migrating your project to Managed C++ to take advantage of the conveniences it provides.

The other solution for you would be to provide the user with some kind of boilerplate code that implements try/catch inside every DLL API function. Then instruct the user to modify the wrapped functions.

extern "C"
{
  __declspec(dllexport) int __cdecl MyFunction(void)
  {
    try
    {
      MyFunctionImpl();
      return 0; // Return a success code
    }
    catch (...)
    {
      return 1; // Return an error code
    }
  }
}

void MyFunctionImpl(void)
{
  // User implements custom scripting here...
}

Romen
  • 1,617
  • 10
  • 26