Skip to content

Instantly share code, notes, and snippets.

@wildmichael
Last active July 4, 2018 17:28
Show Gist options
  • Save wildmichael/4602341 to your computer and use it in GitHub Desktop.
Save wildmichael/4602341 to your computer and use it in GitHub Desktop.
to_python converter sample to demonstrate the make_getter problem.
import os, sys
from distutils.core import setup, Extension
setup(name='stringTest',
ext_modules = [
Extension('_string', [
'string.cpp'
],
include_dirs = [
'/usr/include/qt4'
],
libraries = [
'boost_python-py%d%d'%sys.version_info[:2],
'QtCore'
],
),
],
)
// Most of this code is from http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters
#include <boost/python.hpp>
#include <QtCore/QString>
struct QString_to_python_str
{
static PyObject* convert(QString const& s)
{
return boost::python::incref(
boost::python::object(
s.toLatin1().constData()).ptr());
}
};
struct QString_from_python_str
{
QString_from_python_str()
{
boost::python::converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<QString>());
}
// Determine if obj_ptr can be converted in a QString
static void* convertible(PyObject* obj_ptr)
{
if (!PyString_Check(obj_ptr)) return 0;
return obj_ptr;
}
// Convert obj_ptr into a QString
static void construct(
PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data* data)
{
// Extract the character data from the python string
const char* value = PyString_AsString(obj_ptr);
// Verify that obj_ptr is a string (should be ensured by convertible())
assert(value);
// Grab pointer to memory into which to construct the new QString
void* storage = (
(boost::python::converter::rvalue_from_python_storage<QString>*)
data)->storage.bytes;
// in-place construct the new QString using the character data
// extraced from the python object
new (storage) QString(value);
// Stash the memory chunk pointer for later use by boost.python
data->convertible = storage;
}
};
void initializeConverters()
{
using namespace boost::python;
// register the to-python converter
to_python_converter<
QString,
QString_to_python_str>();
// register the from-python converter
QString_from_python_str();
}
struct A
{
static std::string staticStdString;
static QString staticQString;
};
std::string A::staticStdString("foo");
QString A::staticQString("bar");
BOOST_PYTHON_MODULE(_string)
{
using namespace boost::python;
initializeConverters();
class_<A>("A")
.add_static_property("staticStdString", make_getter(A::staticStdString))
.add_static_property("staticQString1",
make_getter(A::staticQString,
// >>>>>> FAILURE WITHOUT THIS POLICY <<<<<<<
return_value_policy<return_by_value>()))
.add_static_property("staticQString2",
// >>>>>> NOTICE, HERE WITHOUT A POLICY <<<<<<<
// Message: "No Python class registered for C++ class QString"
make_getter(A::staticQString))
;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment