python调用c返回字符串,从暴露给Python的C ++函数返回int或字符串

Using Boost Python, is it possible for a C++ function exposed to python to return either an integer or a string (or other type) depending on the value of the single argument passed in?

So in Python I want to do this:

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++ pseudo code (obviously won't it work like this, but you get the idea)

???? 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);

}

If it makes any difference, I'm using Boost 1.48 with Python 3.2.

解决方案

Have the C++ function return a boost::python::object. The object constructor will attempt to

converts its argument to the appropriate python type and manages a reference to it. For example, boost::python::object(42) will return a Python object with a Python type of int.

Here is a basic example:

#include

/// @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);

}

and its usage:

>>> import example

>>> x = example.get_value("string")

>>> x

'string 42'

>>> type(x)

>>> x = example.get_value("int")

>>> x

42

>>> type(x)

>>> x = example.get_value("")

>>> x

>>> type(x)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值