避免使用boost::python::extract
#include
namespace py = boost::python;
int getIntValue(py::object obj) {
py::extract extractor(obj);
if (extractor.check()) {
// 提取int值
int value = extractor();
return value;
}
// 提取失败,返回默认值
return 0;
}
int main() {
py::object obj1(10);
int result1 = getIntValue(obj1);
std::cout << "Result 1: " << result1 << std::endl;
py::object obj2("not an int");
int result2 = getIntValue(obj2);
std::cout << "Result 2: " << result2 << std::endl;
return 0;
}
在上面的示例中,getIntValue
函数使用boost::python::extract
来尝试提取传入的Python对象中的int值。如果提取成功,则返回提取到的值;否则,返回默认值0。这样可以避免使用boost::python::extract
可能引发的异常。
上一篇:避免使用bind的箭头函数