title: How do I copy a part of bytearray to c_void_p-referenced memory and vice versa?
body: <p>In the Python application, I have a bytearray with some data. My python code is called by some external native library (DLL/so/dylib) (using ctypes and its <a href="https://docs.python.org/3.8/library/ctypes.html#callback-functions" rel="nofollow noreferrer">callback functions</a>). One of the callback functions includes a pointer to the unmanaged buffer, allocated in that external library. </p>
  
  <p>I need to copy a part of the bytearray into this unmanaged buffer or copy contents of the unmanaged buffer into the bytearray at specific location. </p>
  
  <p>To put it simply, I have </p>
  
  <pre><code>def copy_from_python_callback(c_void_p_parameter : c_void_p, offset : int, size : int):
    managed_buf = bytearray(some_size) # suppose we have data in this buffer already
    unmanaged_buf = c_void_p_parameter
    # what do I need to do here?
    # src_buf = pointer_to_specific_byte_in_managed_buf
    memmove(unmanaged_buf, src_buf, size)
  
  def copy_to_python_callback(c_void_p_parameter : c_void_p, offset : int, size : int):
    managed_buf = bytearray(some_size) #some_size is assumed to be larger than offset + size
    unmanaged_buf = c_void_p_parameter
    # what do I need to do here?
    # dst_buf = pointer_to_specific_byte_in_managed_buf
    memmove(dst_buf, unmanaged_buf, size)
  </code></pre>
  
  <p>In other languages, the answer would be simple - I'd either call the dedicated method (e.g. in .NET Framework's Marshal class), or get the pointer to the specific byte in the bytearray (in native languages like C++ or Pascal) and be done. Unfortunately, I don't see how to do either of these operations in Python without an intermediate bytes() or similar buffer. </p>
  
  <p>I have some methods which use the intermediate bytes() instance, but copying the data just because there's no way to get a pointer seems to be weird to me. </p>
  
  <p>I am looking for version-independent solution, if possible, but can live with python3-only one as well. Thank you in advance. </p>