【发布时间】:2014-05-27 08:53:07
【问题描述】:
我读到了这个问题Ctypes catching exception 但就我而言,当我尝试从 C++ 抛出异常时,python.exe 总是崩溃。
我的代码和上一个问题一样:
C++:
double Divide(double a, double b)
{
if (b == 0)
{
throw new invalid_argument("b cannot be zero!");
}
return a / b;
}
Python:
from ctypes import *
mathdll=cdll.MathFuncsDll
divide = mathdll.Divide
divide.restype = c_double
divide.argtypes = [c_double, c_double]
try:
print divide (10,0)
except WindowsError:
print "lalal"
except:
print "dada"
我使用 Windows 7 x64、python 2,7 和 MinGW
是否有一些提示或技巧可以在 python 中使用 ctypes 处理来自 C++ 的异常?
【问题讨论】:
-
Ctypes catching exception 中的任何答案都没有真正解释 @nobs 如何通过抛出 C++ 异常在 Python 中引发异常。我可能会用 C++ 示例扩展我的答案并将其重新发布到那里。
-
这是特定于 Visual C++ 的。对于 MinGW,这是不可能的,AFAIK。 C 绑定需要捕获所有异常并将它们转换为错误返回代码。您可以用 C++ 编写 Python 扩展模块,而不是使用带有 C API 的 ctypes; Cython 也支持C++ exceptions。
标签: python c++ exception ctypes