Python C类型从C++;
我读了这个问题 但在我的例子中,当我试图从C++抛出异常时,Python .EXE总是崩溃。 我的代码与上一个问题相同: C++: Python:Python C类型从C++;,python,c++,exception,ctypes,Python,C++,Exception,Ctypes,我读了这个问题 但在我的例子中,当我试图从C++抛出异常时,Python .EXE总是崩溃。 我的代码与上一个问题相同: C++: 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 Wi
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"
我使用windows7x64、python2、7和MinGW
有什么技巧或技巧,如何使用CyType在Python中处理C++异常?< /P> < PcType不支持C++异常,或者C++什么都不支持。给定其Windows根,ctypes有一个用于Windows结构化异常处理(SEH)的处理程序。用Visual C++编写的库通过SEH(代码<代码> 0xE06D7363实现C++细节,参见实现细节),但是MinGW不支持C中的SEH,也不使用它来实现C++异常。 如果您不关心使代码跨平台,那么可以调用Windows API。ctypes将SEH异常路由到Python
OSError
。使用\uuuu try
和\uu(除
关键字外)设置SEH处理程序(Microsoft扩展C)。对多个异常代码进行特殊处理,否则从Windowserr(code)跳转到PyErr\u SetFromWindowsErr(code)
例如:
#包括
__declspec(dllexport)无效测试()
{
RaiseException(42,0,0,NULL);
}
测试:
>>从ctypes导入*
>>>lib=CDLL('./lib.dll')
>>>lib.test()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
操作错误:[WinError 42]Windows错误0x%X
(显然,代码< PyryStEngEndoWORSER R >代码中有一个错误。格式代码<代码> %x < /COD>不支持;只有小写<代码> %x。假装最后一部分是代码> Windows错误0x2a<代码>)。实际上没有答案解释@ NoB如何通过抛出C++异常在Python中引发异常。我可能会用C++的例子来扩展我的答案,并在那里重新发布。这是VisualC++的专一。对MinGW来说这是不可能的,好吧。C绑定需要捕获所有异常并将其转换为错误返回代码。而不是使用C API使用cType,可以在C++中编写Python扩展模块;Cython也支持。
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"