title: What is the most efficient way to copy an externally provided buffer to bytes
body: <p>I am interfacing to an external library using ctypes. This library returns to me a binary buffer. The interface looks like this:</p>
  
  <pre><code>int getBuff(unsigned char **buf, int *len);
  </code></pre>
  
  <p>The library also exports a deallocator so that I can free the buffer when I am done with it, but that aspect presents no problems to me, so I don't think we need to cover it.</p>
  
  <p>In my ctypes code I am representing the <code>buf</code> argument as <code>c_void_p</code>. I would like to copy this buffer into a bytes object as efficiently as possible.</p>
  
  <p>At the moment I have:</p>
  
  <pre><code>data = bytes(bytearray(ctypes.cast(buf, ctypes.POINTER(ctypes.c_ubyte*len.value))[0]))
  </code></pre>
  
  <p>where <code>buf</code> is <code>c_void_p</code> and <code>len</code> is <code>c_int</code>.</p>
  
  <p>As I understand it, this performs two copies. Once to the bytearray object, and then again to the bytes object.</p>
  
  <p>How can I do this with only a single copy? </p>
  
  <p>My current efforts have concentrated on Python 2, but in due course I will need to support this for Python 3 as well.</p>