覆盖C代码以引发C ++异常? [英] Override C code to throw a C++ exception?

查看:88
本文介绍了覆盖C代码以引发C ++异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C库(可从C和C ++代码调用),只需退出即可处理无效输入。看起来像这样

I have a C library (callable from C and C++ code) which handles invalid input by simply exiting. It looks like this

#ifdef __cplusplus
extern "C" {
#endif

void exitWithError(const char* func) {
    printf("woopsie in %s", func);
    exit(1);
}

void myfunc(int i) {
    if (i < 0)
        exitWithError(__func__);
}

#ifdef __cplusplus
}
#endif

即使与C ++代码链接,该库仍以 C模式编译。即使用

This library is compiled in "C mode", even when linked with C++ code. I.e. using

g++ -x c <abovelibrary.c>

我正在C ++代码中使用此库,并希望它引发异常以代替退出。例如,

I'm using this library in C++ code, and desire it to throw an exception, in lieu of exiting. E.g.

void exitWithError(const char* func) {
    throw std::invalid_argument( func );
}

是否可以使用预处理程序指令重新定义 exitWithError ,因此它会向外部调用C ++代码引发异常,但仍与内部调用C代码兼容?

Is it possible to use pre-processor directives to redefine exitWithError in C++, so that it throws an exception to the external calling C++ code, but is still compatible by the internal calling C code?

是否可以在不修改原始C库的情况下进一步做到这一点(尽管这不是严格的要求)?

Can this further be done without modifying the original C library (although this is not a strict requirement)?

对于上下文,我使用的是C ++ Catch2库测试基础C库,并希望测试是否正确处理了无效的用户输入(使用Catch2的 REQUIRE_THROWS 宏)。如果这很重要,我将使用C ++ 14,并且C库符合C99。

For context, I'm using the C++ Catch2 library to unit test the underlying C library, and wish to test that invalid user inputs are being correctly handled (using Catch2's REQUIRE_THROWS macro). I'm using C++14 if that matters, and the C library conforms to C99.

推荐答案

按照这个问题,我们可以将 exitWithError 声明为C库中的弱符号

As per this question, we can declare exitWithError as a weak symbol from within the C library

#pragma weak exitWithError
void exitWithError(const char* func) {
    printf("woopsie in %s", func);
    exit(1);
}

并在C ++中重新定义它,引发异常。

and redefine it in C++, throwing an exception.

extern "C" void exitWithError(const char* func) {
    throw std::invalid_argument(func);
}

正如评论中指出的那样,必须绝对确保他们了解内部调用 exitWithError 时C库的状态,因此在捕获到异常后可以安全地继续。

As pointed out in the comments, one must be absolutely sure they understand the internal state of the C library when exitWithError is invoked, and hence that it's safe to continue after catching the exception.

这篇关于覆盖C代码以引发C ++异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆