覆盖 C 代码以抛出 C++ 异常?
Override C code to throw a C++ exception?
我有一个 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 mode" 中编译的,即使在与 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。
根据 C 库中的 , we can declare exitWithError
as a weak symbol
#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++ 代码调用),它通过简单地退出来处理无效输入。看起来像这样
#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 mode" 中编译的,即使在与 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。
根据 C 库中的 exitWithError
as a weak symbol
#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 库的内部状态,因此在捕获异常后继续是安全的。