gpt4 book ai didi

c++ - 覆盖 C 代码以抛出 C++ 异常?

转载 作者:太空宇宙 更新时间:2023-11-04 12:31:17 26 4
gpt4 key购买 nike

我有一个 C 库(可从 C 和 C++ 代码调用),它通过简单地退出来处理无效输入。看起来像这样

#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++ 代码链接时也是如此。 IE。使用

g++ -x c <abovelibrary.c>

我在 C++ 代码中使用这个库,并希望它抛出异常,而不是退出。例如

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

是否可以在C++中使用预处理器指令重新定义exitWithError,使其对外部调用C++代码抛出异常,但仍然兼容内部调用C代码?

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

对于上下文,我正在使用 C++ Catch2 库对底层 C 库进行单元测试,并希望测试是否正确处理了无效的用户输入(使用 Catch2 的 REQUIRE_THROWS 宏)。如果重要的话,我正在使用 C++14,并且 C 库符合 C99。

最佳答案

根据 this question , 我们可以将 exitWithError 声明为 weak symbol来自 C 库中

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

并在 C++ 中重新定义它,抛出异常。

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

正如评论中所指出的,当调用 exitWithError 时,必须绝对确定他们了解 C 库的内部状态,因此在捕获异常后继续是安全的。

关于c++ - 覆盖 C 代码以抛出 C++ 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58550903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com