<div dir="ltr">The problem with your current code is that as soon as you call src_hndl.Free() the pointer is not necessarily valid any more! .NET is allowed to move the memory contents of objects at will unless they are pinned (which is what the first line does). By freeing the GCHandle it is no longer pinned and liable to move/freed as the garbage collector compacts memory. Also, in 64-bit Python, you will need to call ToInt64() instead of ToInt32(). In fact, it may always be reasonable to call ToInt64() since Python's integer type will likely deal with it being 32 or 64-bit automatically.<div>

<br></div><div>So all in all:</div><div><ul><li>Use ToInt64() instead of ToInt32(), at least in 64-bit Python (e.g. x.ToInt64() if ctypes.sizeof(ctypes.c_void_p) == 8 else x.ToInt32())</li><li>Do not call GCHandle.Free() until you are completely done with the memory pointer, but make sure you definitely call it after you are done with the memory pointer because otherwise the garbage collector can never free or move the memory that is pinned (resulting in memory leaks or fragmentation)</li>

</ul><div><div>Jeff</div></div></div></div><div class="gmail_extra"><br><br><div class="gmail_quote">On Fri, May 23, 2014 at 3:34 AM, Dave Cook <span dir="ltr"><<a href="mailto:daverz@gmail.com" target="_blank">daverz@gmail.com</a>></span> wrote:<br>

<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">(Sorry for screwing up the thread; I messed up my list subscription.<br>
This is a response to<br>
<a href="https://mail.python.org/pipermail/pythondotnet/2014-May/001525.html" target="_blank">https://mail.python.org/pipermail/pythondotnet/2014-May/001525.html</a> )<br>
<br>
Thanks, Jeffrey, that's awesome.  Since the pointer can be directly<br>
accessed, np.frombuffer() can be used to avoid a copy.<br>
<br>
src_hndl = GCHandle.Alloc(src, GCHandleType.Pinned)<br>
try:<br>
    src_ptr = src_hndl.AddrOfPinnedObject().ToInt32()<br>
    bufType = ctypes.c_double*len(src)<br>
    cbuf = bufType.from_address(src_ptr)<br>
    dest = np.frombuffer(cbuf, dtype=cbuf._type_)<br>
finally:<br>
    if src_hndl.IsAllocated: src_hndl.Free()<br>
<span class="HOEnZb"><font color="#888888"><br>
Dave Cook<br>
_________________________________________________<br>
Python.NET mailing list - <a href="mailto:PythonDotNet@python.org">PythonDotNet@python.org</a><br>
<a href="https://mail.python.org/mailman/listinfo/pythondotnet" target="_blank">https://mail.python.org/mailman/listinfo/pythondotnet</a><br>
</font></span></blockquote></div><br></div>