[IronPython] memoryview / passing string data to a C function without copying

Peter Schwalm ps at peter-schwalm.de
Wed Jun 1 05:01:50 CEST 2011


Hi,

I am looking for an efficient way to pass a string to a c++ function.

In CPython this function works on binary (byte) data usually read in 
from a file. Now I need an Ironpython version.

Although I am not happy with it I can live with the automatic 
transformation of (binary) file data into unicode strings during reading 
and writing. So I have modified my C++ function to work on wide chars 
(i.e. unicode chars).

Now I am looking for a way to pass the unicode string to the c++ 
function efficiently, i.e. without copying or modifying it before the 
call. I found memoryview and thought it is what I need. But as far as I 
see it works only with byte strings.

     x2              = b"abc"                # byte string
     view2           = memoryview(x2)        # ok

     x3              = "abc"
#   the following code line results in:     # char string
#   "error: TypeError: expected IBufferProtocol, got str"
     view3           = memoryview(x3)        # error

My questions:

     Why does memory view not work here?

     Does anyone know how to pass the contents of a string to a C 
function without copying it?

The context I am working with is roughly as follows:
...
import ctypes as ct
...
     self.dll = ct.cdll.LoadLibrary(dllPath)
     cObject = self.dll.ctor()
     self.dll.cFunc(cObject, source, destination, length)

where cFunc is the exported name of the c function, and cObject is the 
address of a housekeeping object allocated in the C-dll via C++ new and 
returned by the ctor function. Source should provide the string data to 
the C function in a suitable and efficient form, and for destination I 
used an "array.array("H", length).

Thanks in advance
Peter








More information about the Ironpython-users mailing list