[Python.NET] Efficient copy of .NET Array to ctypes or numpy array.

Dave Cook daverz at gmail.com
Fri May 23 12:34:00 CEST 2014


(Sorry for screwing up the thread; I messed up my list subscription.
This is a response to
https://mail.python.org/pipermail/pythondotnet/2014-May/001525.html )

Thanks, Jeffrey, that's awesome.  Since the pointer can be directly
accessed, np.frombuffer() can be used to avoid a copy.

src_hndl = GCHandle.Alloc(src, GCHandleType.Pinned)
try:
    src_ptr = src_hndl.AddrOfPinnedObject().ToInt32()
    bufType = ctypes.c_double*len(src)
    cbuf = bufType.from_address(src_ptr)
    dest = np.frombuffer(cbuf, dtype=cbuf._type_)
finally:
    if src_hndl.IsAllocated: src_hndl.Free()

Dave Cook


More information about the PythonDotNet mailing list