在加载的共享库中捕获异常

catching an exception in a loaded shared library

本文关键字:捕获异常 共享 加载      更新时间:2023-10-16

捕获在加载的共享库中抛出的异常是否可移植?我注意到它与dlfcn.h一起工作,但我想知道这种行为是否普遍预期,例如在windows上使用LoadLibrary时?

示例代码:

main.cpp :

#include <stdexcept>
#include <cstdio>
#include <dlfcn.h>
typedef void(*dummy_t)();
int main()
{
    dummy_t f;
    void* handle;
    handle = dlopen("module.so", RTLD_LAZY);
    f = (dummy_t)dlsym(handle, "modulemain");
    try
    {
        f();
    }
    catch(std::runtime_error& e)
    {
        fprintf(stderr, "caught exception: %sn", e.what());
    }
    dlclose(handle);
}

module.cpp :

#include <stdexcept>
extern "C" void modulemain()
{
    throw std::runtime_error("some terrible error occured");
}

是的,在Windows下应该可以正常工作。