title: Efficient way to convert string to ctypes.c_ubyte array in Python
body: <p>I have a string of 20 bytes, and I would like to convert it a <code>ctypes.c_ubyte</code> array for bit field manipulation purposes.</p>
  
  <pre><code> import ctypes
   str_bytes = '01234567890123456789'
   byte_arr = bytearray(str_bytes)
   raw_bytes = (ctypes.c_ubyte*20)(*(byte_arr))
  </code></pre>
  
  <p>Is there a way to avoid a deep copy from str to bytearray for the sake of the cast?</p>
  
  <p>Alternatively, is it possible to convert a string to a bytearray without a deep copy? (With techniques like memoryview?)</p>
  
  <p>I am using Python 2.7.</p>
  
  <p><strong>Performance results:</strong></p>
  
  <p>Using <a href="https://stackoverflow.com/a/21490290/1445644">eryksun</a> and <a href="https://stackoverflow.com/a/21492025/1445644">Brian Larsen</a>'s suggestion, here are the benchmarks under a vbox VM with Ubuntu 12.04 and Python 2.7.</p>
  
  <ul>
  <li>method1 uses my original post </li>
  <li>method2 uses ctype from_buffer_copy</li>
  <li>method3 uses ctype cast/POINTER </li>
  <li>method4 uses numpy</li>
  </ul>
  
  <p>Results:</p>
  
  <ul>
  <li>method1 takes 3.87sec</li>
  <li>method2 takes 0.42sec</li>
  <li>method3 takes 1.44sec</li>
  <li>method4 takes 8.79sec</li>
  </ul>
  
  <p>Code:</p>
  
  <pre><code>import ctypes
  import time
  import numpy
  
  str_bytes = '01234567890123456789'
  
  def method1():
      result = ''
      t0 = time.clock()
      for x in xrange(0,1000000):     
          byte_arr = bytearray(str_bytes)
          result = (ctypes.c_ubyte*20)(*(byte_arr))
  
      t1 = time.clock()
      print(t1-t0)
  
      return result
  
  def method2():
  
      result = ''
      t0 = time.clock()
      for x in xrange(0,1000000):     
          result = (ctypes.c_ubyte * 20).from_buffer_copy(str_bytes)
  
      t1 = time.clock()
      print(t1-t0)
  
      return result
  
  def method3():
  
      result = ''
      t0 = time.clock()
      for x in xrange(0,1000000):     
          result = ctypes.cast(str_bytes, ctypes.POINTER(ctypes.c_ubyte * 20))[0]
  
      t1 = time.clock()
      print(t1-t0)
  
      return result
  
  def method4():
  
      result = ''
      t0 = time.clock()
      for x in xrange(0,1000000):     
          arr = numpy.asarray(str_bytes)
          result = arr.ctypes.data_as(ctypes.POINTER(ctypes.c_ubyte*len(str_bytes)))
  
      t1 = time.clock()
      print(t1-t0)
  
      return result
  
  print(method1())
  print(method2())
  print(method3())
  print(method4())
  </code></pre>