This can be accomplished in the same manner that one would return Tribool
from a Python method. In either language, one needs to obtain a handle to the Tribool
Python class object, and then invoke it. The object returned will be an instance of the Tribool
type.
For example:
from tribool import Tribool
x = Tribool(False)
is equivalent to:
namespace python = boost::python;
python::object tribool_class = python::import("tribool").attr("Tribool");
python::object x = tribool_class(false);
Below is a simplified example where a user defined Python module (spam
) contains a Python class (Spam
), and a C++ Python extension module (example
) provides a make_spam
function that creates spam.Spam
objects.
The spam.py
Python module:
class Spam(object):
def __init__(self, value):
self.value = value
def __str__(self):
return self.__repr__() + " has a value of " + str(self.value)
The example.cpp
extension module:
#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);
}
Interactive Python:
>>> import example
>>> print example.make_spam(False)
<spam.Spam object at 0xb74be1ac> has a value of False
>>> print example.make_spam(True)
<spam.Spam object at 0xb74be10c> has a value of True
>>> print example.make_spam(None)
<spam.Spam object at 0xb74be1ac> has a value of None