gpt4 book ai didi

python - 如何在 python 中捕获异常(由 C++ 引起)

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:42 35 4
gpt4 key购买 nike

我想在我的 C++ 应用程序中嵌入 python。我不使用 Boost 库。

如果 C++ 函数抛出异常,我想捕获它并在我的应用程序中打印错误,或者获取一些详细信息,例如导致错误的 python 脚本中的行号。

我该怎么做?我在 Python API 或 C++ 中找不到任何函数来获取详细的异常信息。

void sum(int iA, int iB)
{
throw iA + iB;
}

from ctypes import *

mydll = WinDLL("C:\\Users\\cppwrapper.dll")

try:
mydll.sum(2,3)
catch:
print "exception occured"

但它不起作用。请帮我解决这个问题。提前致谢。

最佳答案

您需要做的是在您的 C++ 函数中捕获异常,然后将其转换为 Python 异常并将其返回给 Python 代码(详见 the manual)。像这样的东西:

PyObject method(...)
{
try {
res = do_stuff();
return res;
}
catch(SomeException e)
{
PyErr_SetObject(exception_type, message);
return NULL;
}
catch(...)
{
PyErr_SetObject(PyErr_SystemError, "Unexpected exception in C++");
return NULL;
}
}

如果您在返回 python 之前没有捕获异常,则异常可能会通过 python 解释器,并可能掉落到调用 python 解释器的 C++ 函数。这可能是处理异常的一种糟糕方法,因为 python 解释器将无法进行清理。省略号只是为了确保不会发生这种情况。

关于python - 如何在 python 中捕获异常(由 C++ 引起),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32391561/

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