【发布时间】:2015-12-04 09:35:40
【问题描述】:
我想在 python 应用程序中嵌入 C++。我不想使用 Boost 库。
如果 C++ 函数进行断言,我想在我的 python 应用程序中捕获它并打印错误,或者获取一些详细信息,例如导致错误的 python 脚本中的行号。主要是“我想在 python 执行流程中继续前进”
我该怎么做?我在 Python API 或 C++ 中找不到任何函数来获取详细的断言信息。
C++ 代码
void sum(int iA, int iB)
{
assert(iA + iB >10);
}
Python 代码
from ctypes import *
mydll = WinDLL("C:\\Users\\cppwrapper.dll")
try:
mydll.sum(10,3)
catch:
print "exception occurred"
# control should go to user whether exceptions occurs, after exception occurs if he provide yes then continue with below or else abort execution, I need help in this part as well
import re
for test_string in ['555-1212', 'ILL-EGAL']:
if re.match(r'^\d{3}-\d{4}$', test_string):
print test_string, 'is a valid US local phone number'
else:
print test_string, 'rejected'
提前致谢。
【问题讨论】:
-
断言也不例外。因此它无法被捕获,无论是在 python 中还是在 C++ 中。
-
assert调用abort,所以最终你无法阻止终止进程。但是您可以使用 ctypes 将回调函数安装为SIGABRT处理程序(Python 自己的信号系统将无法工作,因为它是异步的)。对于微软的 CRT,您也可以调用_set_abort_behavior来禁用错误报告。在SIGABRT处理程序中,您可以调出如下调试控制台:local = sys._getframe(1).f_locals;code.interact('Debug Console', local=local)。 -
Python 的信号处理程序不起作用。它是通过为解释器设置一个标志并返回来实现的,因此该进程将在处理程序运行之前很久就被终止。您需要改用 ctypes 回调。要创建回调,只需使用
@CFUNCTYPE(None, c_int)装饰函数定义。回调是通过在 POSIX 系统(如 Linux)中调用CDLL(None).signal(SIGABRT, callback)来安装的。在 Windows 中使用CDLL(ctypes.util.find_library('c'))而不是CDLL(None),但在 Python 3.5+ 中使用CDLL('ucrtbase')。 -
@eryksun 我正在使用 python python 2.7.10,我无法切换到 3.5+,如果您提供代码示例,我们将不胜感激。我对操作系统概念真的很陌生。
标签: python c++ windows ctypes assertions