在扩展模块中为用户定义的python类提升Python to_python_converter

时间:2013-12-29 07:32:11

标签: c++ python boost boost-python

我想从我的C ++扩展模块返回以下python类的实例,它模仿boost :: tribool的三个状态逻辑:

class Tribool(object):

def __init__(self, value = None):
    if any(value is v for v in (False, True, None)):
        self.value = value
    else:
        raise ValueError("Tribool must be False, True or None")

def __nonzero__(self):
    raise TypeError("Tribool may not be used as an implicit bool")

def __eq__(self, other):
    if isinstance(other, Tribool):
        return self.value is other.value
    if any(other is v for v in (False, True, None)):
        return self.value is other
    raise TypeError("Tribool can only be compared to another Tribool or False, True, or None")

def __ne__(self, other):
    return not (self == other)

def __invert__(self):
    if self.value is False:
        return Tribool(True)
    elif self.value is True:
        return Tribool(False)
    elif self.value is None:
        return Tribool(None)
    raise ValueError("Tribool must be False, True or None")

def __and__(self, other):
    if (self.value is False) or (other.value is False):
        return Tribool(False)
    if (self.value is None) or (other.value is None):
        return Tribool(None)
    return Tribool(True)

def __or__(self, other):
    if (self.value is True) or (other.value is True):
        return Tribool(True)
    if (self.value is None) or (other.value is None):
        return Tribool(None)
    return Tribool(False)

def __xor__(self, other):
    if (self.value is None) or (other.value is None):
        return Tribool(None)
    if self == other:
        return Tribool(False)
    return Tribool(True)

def __str__(self):
    if any(self.value is v for v in (False, True, None)):
        return str(self.value)
    raise ValueError("Tribool must be False_, True_ or Maybe_")

def __repr__(self):
    return "Tribool(%s)" % str(self)

我相信我需要编写一个to_python_converter,但我无法弄清楚如何为用户定义的python类型编写转换器。我已经阅读了Boost Python文档并在Google上进行了搜索,但没有找到一个很好的例子。任何帮助表示赞赏。


更新

以下C ++代码会将tribool转换为Python值True,False和None,这是一个部分解决方案:

struct tribool_to_Tribool
{
    static PyObject *convert(tribool const& value)
    {
        if (value == true) return boost::python::incref(boost::python::object(true).ptr());
        else if (value == false) return boost::python::incref(boost::python::object(false).ptr());
        else return boost::python::incref(boost::python::object().ptr());
    }
};

to_python_converter<tribool,tribool_to_Tribool>();

我无法弄清楚的部分是如何从转换例程返回纯Python Tribool类的实例而不是值True,False和None。

1 个答案:

答案 0 :(得分:1)

这可以通过从Python方法返回Tribool的方式完成。在任何一种语言中,都需要获取Tribool Python类对象的句柄,然后调用它。返回的对象将是Tribool类型的实例。

例如:

from tribool import Tribool
x = Tribool(False)

相当于:

namespace python = boost::python;
python::object tribool_class = python::import("tribool").attr("Tribool");
python::object x = tribool_class(false);

下面是一个简化示例,其中用户定义的Python模块(spam)包含Python类(Spam),而C ++ Python扩展模块(example)提供了{{ 1}}创建make_spam个对象的函数。

spam.Spam Python模块:

spam.py

class Spam(object): def __init__(self, value): self.value = value def __str__(self): return self.__repr__() + " has a value of " + str(self.value) 扩展模块:

example.cpp

Interactive Python:

#include <boost/python.hpp>

boost::python::object make_spam(boost::python::object value)
{
  // from spam import Spam
  // return Spam(value)
  return boost::python::import("spam").attr("Spam")(value);
}

BOOST_PYTHON_MODULE(example)
{
  boost::python::def("make_spam", &make_spam);
}