On 10/25/2010 10:51 AM, Marek Denis wrote:
Hi,
While I had some questions concerning accessing objects in Python, that
were previously created in C++ now I'd like to know whether it's
possible to get access to the raw memory from Python layer.
Let's suppose I have the char* ptr pointer that points to the memory
chunk with IPv4 packet. I would like to be able to read (and preferably
write) data from Python layer (not via wrapped object that contains
char* ptr and has some methods to write/read data), but without making
any memory copies.
I can use struct (even define format dynamically) in Python, but I don't
know how do I pass the proper pointer from C++. If I use
boost::python::object I had problems that script didn't know char type.
I can use boost::python::str, return it and use in Python but I suppose
it does copy data into str object, right?

If not Boost, maybe basic Python C API would work?

BTW. Suppose I had char* txt = "some string";
How do i create boost::python::object() that would containt the whole
string? Passing *txt or txt into boost::python::object(*txt) didn't work.


If it's okay for that data to be totally opaque in Python, then you probably want to look into PyCObject in the Python C API. The Python str type does not support pointing at memory it doesn't own, so it sounds like that isn't an option for you.

If you want to interpret it in some way so that native Python code can understand it, you'll need to use Numpy. I've written a low-level Boost.Python interface to Numpy that you might find useful in that case here:

http://svn.boost.org/svn/boost/sandbox/numpy/

...but it will still be pretty complicated. Passing raw memory into Python is hard precisely because it's very hard to do the memory management in a safe way.


Jim Bosch
_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to