使用Boost Python,暴露给python的C ++函数是否可能根据传入的单个参数的值返回整数或字符串(或其他类型)?
所以在Python中我想这样做:
from my_module import get_property_value
# get an integer property value
i = get_property_value("some_int_property")
# get a string
s = get_property_value("some_string_property")
C ++伪代码(显然,它不会像这样工作,但您会明白的)
???? getPropertyValue(const char* propertyName)
{
Property *p = getProperty(propertyName);
switch(p->type)
{
case INTEGER: return p->as_int();
case STRING: return p->as_string();
...
}
}
BOOST_PYTHON_MODULE(my_module)
{
boost::python::def("get_property_value", &getPropertyValue);
}
如果有什么不同,我将在Python 3.2中使用Boost 1.48。
让C ++函数返回boost::python::object
。该object
构造函数将尝试将其参数转换为适当的Python类型和管理一个参考吧。例如,boost::python::object(42)
将返回Python类型为的Python对象int
。
这是一个基本示例:
#include <boost/python.hpp>
/// @brief Get value, returning a python object based on the provided type
/// string.
boost::python::object get_value(const std::string& type)
{
using boost::python::object;
if (type == "string") { return object("string 42"); }
else if (type == "int") { return object(42); }
return object(); // None
}
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::def("get_value", &get_value);
}
及其用法:
>>> import example
>>> x = example.get_value("string")
>>> x
'string 42'
>>> type(x)
<type 'str'>
>>> x = example.get_value("int")
>>> x
42
>>> type(x)
<type 'int'>
>>> x = example.get_value("")
>>> x
>>> type(x)
<type 'NoneType'>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句