2012-11-23 21:43:42 +01:00
|
|
|
// Copyright Daniel Wallin 2006. Use, modification and distribution is
|
|
|
|
// subject to the Boost Software License, Version 1.0. (See accompanying
|
|
|
|
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
|
|
|
|
2016-04-08 04:45:23 +02:00
|
|
|
#include "boost_python.hpp"
|
2012-11-23 21:43:42 +01:00
|
|
|
#include <string>
|
|
|
|
|
|
|
|
using namespace boost::python;
|
|
|
|
|
|
|
|
struct unicode_from_python
|
|
|
|
{
|
|
|
|
unicode_from_python()
|
|
|
|
{
|
|
|
|
converter::registry::push_back(
|
|
|
|
&convertible, &construct, type_id<std::string>()
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
static void* convertible(PyObject* x)
|
|
|
|
{
|
|
|
|
#if PY_VERSION_HEX >= 0x03020000
|
2017-01-15 06:45:17 +01:00
|
|
|
return PyBytes_Check(x) ? x : PyUnicode_Check(x) ? x : nullptr;
|
2012-11-23 21:43:42 +01:00
|
|
|
#else
|
2016-07-10 04:36:14 +02:00
|
|
|
return PyString_Check(x) ? x : PyUnicode_Check(x) ? x : nullptr;
|
2012-11-23 21:43:42 +01:00
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
|
|
|
static void construct(PyObject* x, converter::rvalue_from_python_stage1_data* data)
|
|
|
|
{
|
|
|
|
void* storage = ((converter::rvalue_from_python_storage<
|
|
|
|
std::string>*)data)->storage.bytes;
|
|
|
|
|
|
|
|
if (PyUnicode_Check(x))
|
|
|
|
{
|
2015-06-07 21:16:51 +02:00
|
|
|
PyObject* utf8 = PyUnicode_AsUTF8String(x);
|
2016-07-10 04:36:14 +02:00
|
|
|
if (utf8 == nullptr)
|
2015-06-07 21:16:51 +02:00
|
|
|
{
|
|
|
|
new (storage) std::string();
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
#if PY_VERSION_HEX >= 0x03000000
|
|
|
|
new (storage) std::string(PyBytes_AsString(utf8)
|
|
|
|
, PyBytes_Size(utf8));
|
2012-11-23 21:43:42 +01:00
|
|
|
#else
|
2015-06-07 21:16:51 +02:00
|
|
|
new (storage) std::string(PyString_AsString(utf8)
|
2017-01-15 06:45:17 +01:00
|
|
|
, PyString_Size(utf8));
|
2012-11-23 21:43:42 +01:00
|
|
|
#endif
|
2015-06-07 21:16:51 +02:00
|
|
|
Py_DECREF(utf8);
|
2012-11-23 21:43:42 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
#if PY_VERSION_HEX >= 0x03000000
|
2017-01-15 06:45:17 +01:00
|
|
|
new (storage) std::string(PyBytes_AsString(x)
|
|
|
|
, PyBytes_Size(x));
|
2012-11-23 21:43:42 +01:00
|
|
|
#else
|
2015-06-07 21:16:51 +02:00
|
|
|
new (storage) std::string(PyString_AsString(x)
|
|
|
|
, PyString_Size(x));
|
2012-11-23 21:43:42 +01:00
|
|
|
#endif
|
|
|
|
}
|
|
|
|
data->convertible = storage;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
void bind_unicode_string_conversion()
|
|
|
|
{
|
|
|
|
unicode_from_python();
|
|
|
|
}
|
|
|
|
|