[英]How can I get the Python module and line number that called my C++ function via Boost::Python?
I have a C++ function that is being called from many Python functions via Boost::Python. 我有一个通过Boost :: Python从许多Python函数调用的C ++函数。 When the C++ function detects bad arguments I want to write a log message and continue processing.
当C ++函数检测到错误的参数时,我想编写一条日志消息并继续进行处理。 In that log message I would like to note the Python module and line number that called into C++.
在该日志消息中,我想指出调用C ++的Python模块和行号。 How can I do this?
我怎样才能做到这一点?
I am able to throw an exception from C++ which is translated into a Python exception that I can catch, but that aborts the C++ function which I cannot have. 我能够从C ++引发一个异常,该异常被转换为我可以捕获的Python异常,但是该异常中止了我无法拥有的C ++函数。
For example, let's say I want to log a warning message if factorial() receives a number less than one. 例如,假设我要记录一个警告消息,如果factorial()收到的数字小于一。 Ignore the fact that it can easily handle the case (and does)--my boss wants a warning anyway.
忽略它可以轻松处理案件的事实(确实如此)-无论如何,我的老板想要警告。 ;)
;)
This code can be called from Python directly or from other C++ functions that get called from Python so the C++ stack trace itself isn't very helpful. 可以直接从Python或从Python调用的其他C ++函数中调用此代码,因此C ++堆栈跟踪本身并不是很有用。
int factorial(int n) {
if (n < 1) {
logMsg("invalid n passed to factorial() at %s, line %d",
<python-module>, <python-line-number>);
}
return n <= 1 ? 1 : n * factorial(n - 1);
}
I'm hoping that the Boost::Python library provides this ability from C++. 我希望Boost :: Python库从C ++提供此功能。
The easiest thing that comes to my mind is to wrap the c++ library with a python module and have the python functions wrap the c++ functions. 我想到的最简单的事情是用python模块包装c ++库,并让python函数包装c ++函数。 You have to exchange your c module name with your python module so all the python functions will call the python module instead of the c++ one.
您必须将c模块名称与python模块交换,以便所有python函数都将调用python模块,而不是c ++模块。
mv my_cmodule_name.so -> __my_cmodule_name.so (and change also inside the code its name ) mv my_cmodule_name.so-> __my_cmodule_name.so(并在代码内更改其名称)
#my_cmodule_name.py
import my_cmodule_name as cmod
import traceback
def catchBadArgsDecorator(function):
def _inner(*args,**kwds):
try:
return function(*args, **kdws)
except ValueError:
_, line, function, _ = traceback.extract_stack()[-1]
log("Call to %s(%s) from %s@%d failed" % ( function.__name__, str(args), function,line)
return _inner
# for all your modules functions
myfunction = catchBadArgsDecorator(cmod.myfunction)
The code is untested and can be improved, but I hope you get the idea. 该代码未经测试,可以改进,但是希望您能理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.