title: python: ctypes, read POINTER(c_char) in python
body: <p>I have a ctypes field that is a <code>POINTER(c_char)</code> (it had to be, per the documentation, c_char_p didn't work for my application: <a href="https://docs.python.org/3.7/library/ctypes.html#ctypes.c_char_p" rel="nofollow noreferrer">https://docs.python.org/3.7/library/ctypes.html#ctypes.c_char_p</a>)</p>
  
  <blockquote>
    <p>For a general character pointer that may also point to binary data, POINTER(c_char) must be used.</p>
  </blockquote>
  
  <p>However, this usage recommended by ctypes itself seems to have the downside that, it claims to be a pointer to a single character, however, it isn't, it's a pointer to an array of bytes. </p>
  
  <p>How can I read the array returned by the ctypes fucntion (I know the <code>length</code>) in Python? Trying to index it like <code>foo[0:len]</code> where <code>foo</code> is a <code>POINTER(c_char)</code> blows up with <code>TypeError: 'c_char' object is not subscriptable</code></p>
  
  <p>I can print the first character of the bytestring using either <code>print(foo)</code> or <code>print(foo[0])</code></p>
  
  <p>I was thinking that <code>ctypes.cast</code> might work, however I don't know how to pass it the length of the cast (as in interpret the first N bytes from address foo as a <code>bytes</code> object)</p>
  
  <p>EDIT: some code.</p>
  
  <p>So I have a structure:</p>
  
  <pre><code>class foo(Structure):
  _fields_ = [("state", c_int),
              ("type", c_int),
              ("len", c_int),
              ("payload", POINTER(c_char))]  # according to th following the python bytes are already unsinged https://bytes.com/topic/python/answers/695078-ctypes-unsigned-char
  </code></pre>
  
  <p>And I have another function that returns a <code>POINTER(foo)</code></p>
  
  <pre><code>lib3 = CDLL(....so)
  f = lib3.f
  f.restype = POINTER(foo)
  </code></pre>
  
  <p>I call <code>f</code>, which returns a <code>POINTER(foo)</code>:</p>
  
  <pre><code>ptrf = f(....)
  </code></pre>
  
  <p>And then I was trying to access <code>ptrf.payload</code>. The following code works:</p>
  
  <pre><code>def get_payload(ptr_to_foo):
  
      val = cast(ptr_to_foo.contents.payload, c_char_p).value
      return val[:ptr_to_foo.contents.len]
  </code></pre>
  
  <p>So I do </p>
  
  <pre><code> ptrf = f(....)
   get_payload(ptrf)
  </code></pre>
  
  <p>I was wondering whether the <code>get_payload</code> function would be written more easily. </p>