title: Using ctypes to write callbacks that pass-in pointer to pointer parameters to be used as output-parameter
body: <p>I am using ctypes to interface python code with a legacy C DLL.
  The DLL expects that I give it a function pointer to be used as a callback, that then will be called from within the DLL.</p>
  
  <p>The C declaration of that callback looks like</p>
  
  <pre><code>char foo(char **buf)
  </code></pre>
  
  <p>Semantically the DLL expects that I let point buf to a string buffer that is managed by the callback and return 0 if everything works fine. In C that would be a static char[] variable mybuf and I would pass the address of that static buf back with code like </p>
  
  <pre><code>*buf = &amp;mybuf[0] ;
  return (char)0 ;
  </code></pre>
  
  <p>The string in mybuf needs to be null terminated as usual in C. I was able to pass a function pointer to the DLL and now a python (member) function</p>
  
  <pre><code>def pyfoo(self, char_ptr_ptr) 
  </code></pre>
  
  <p>gets called.</p>
  
  <p>The class in which pyfoo is defined also initialises (in <strong>init</strong>) a field</p>
  
  <pre><code>self.response=create_string_buffer("The Response String")
  </code></pre>
  
  <p>How do I pass the address, where this string is actually stored in memory to the DLL?
  Since ctypes sometimes creates copies instead of returning a real reference by address I tried something like</p>
  
  <pre><code>cpointer = c_int.from_address(char_ptr_ptr[0])
  cpointer.value = addressof(self.response)
  return c_char(0)
  </code></pre>
  
  <p>It does not work.
  I tried other ways of dereferencing the passed pointer-pointer and storing a memory address there (e.g. directly storing (what I think is the address of the string) into char-ptr_ptr[0]), but the caller of the callback is never doing what I am expecting it to do. </p>
  
  <p>If anybody has ever solved the problem to create a null terminated string in python and to pass the address of that string through a **pointer to a DLL implemented in C, I would be very thankful to here about how he/she solved the issue. Thanks!</p>
  
  <p>(Edit) Or is my problem much simpler? Is</p>
  
  <pre><code>c_char(0) 
  </code></pre>
  
  <p>actually pushing a single byte onto the stack as return value? If not, what would be the right way to implement a callback that shall return a single byte?</p>