[C++-sig] Python string -> const char * + size_t
David Abrahams
dave at boost-consulting.com
Sat Jun 11 07:53:54 CEST 2005
Eric Hopper <hopper at omnifarious.org> writes:
> I'm trying to connect a hash function written in C++ to Python. This
> function will be processing a ton of data. In Python, it's quite
> natural to store random data in a string. It's my impression that when
> boost::python converts that string to a ::std::string it makes a copy of
> it.
Of course Python and C++ can't share that representation.
> For this application, that will add a significant amount of CPU to
> the time for processing the data, and that's important.
So convert to a char const* instead.
> I would like instead to pass in pointers that point into the internal
> data structure that Python is storing the string in.
That's what converting to char const* will do.
> The hash function
> is only going to read it and munge it a bit, so as long as the data
> remains around for the duration of the call, it's not a problem.
>
> I want to somehow pass a Python string to an interface something like:
>
> class Something {
> public:
> void hash_data(const char *data, size_t datalen);
> };
>
> What is the easiest and cleanest way to make this happen using
> boost::python?
Well, if you need the length it's a little harder. Make a thin
wrapper function that accepts a boost::python::str object x, then use
x.ptr()
to get the PyObject* and use the Python/C API to get the pointer and length.
HTH,
--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
More information about the Cplusplus-sig
mailing list