title: How to use malloc and free with python ctypes?
body: <p>I have a function in my C library, say <code>runsim()</code> which takes pointer to <code>struct repdata</code> as one of the arguments, where <code>struct repdata</code> is given by</p>
  
  <pre><code>struct repdata {
      int *var1;
      int *var2;
      int *var3;
      char *var4;
      double *var5;
      double *var6;
      int *var7;
  };
  </code></pre>
  
  <p>When using C exclusively, I initialize a variable of type <code>struct repdata</code> calling the function,</p>
  
  <pre><code>struct repdata data;
  void create_data_container(struct repdata *data, int len_data)
  {
  
      data -&gt; var1 = malloc( sizeof(int) * len_data );
      data -&gt; var2 = malloc( sizeof(int) * len_data );
      data -&gt; var3 = malloc( sizeof(int) * len_data );
      data -&gt; var4 = malloc( sizeof(char) * len_data );
      data -&gt; var5 = malloc( sizeof(double) * len_data);
      data -&gt; var6 = malloc( sizeof(double) * len_data);
      data -&gt; var7 = malloc( sizeof(int) * len_data);
  }
  </code></pre>
  
  <p>and then fill this struct as simulation proceeds. After I have written the data to a file, I free the memory using the standard</p>
  
  <pre><code>free(data.var1);
  free(data.var2);
  .
  .
  .
  free(data.var7);
  </code></pre>
  
  <p>I want to call the <code>runsim()</code> function from Python using Python Ctypes. For this I need to pass a pointer to a variable (that is equivalent to the type of <code>struct repdata</code>) as one of the <code>runsim()</code> arguments. Suppose that in Python I have defined an equivalent of <code>struct repdata</code> in the following manner.</p>
  
  <pre><code>import ctypes as C
  
  class Repdata(C.Structure):
      _fields_ = [
          ("var1", C.POINTER(C.c_int)),
          ("var2", C.POINTER(C.c_int)),
          ("var3", C.POINTER(C.c_int)),
          ("var4", C.POINTER(C.c_char)),
          ("var5", C.POINTER(C.c_double)),
          ("var6", C.POINTER(C.c_double)),
          ("var7", C.POINTER(C.c_int)),
      ]
  </code></pre>
  
  <p>What is the equivalent of <code>create_data_container</code> function shown above on the Python side? I want to initialize an instance of Repdata which can be passed to C code and has sufficient memory for storing the replication data. And, once simulation is completed, how do I free the memory from Python?</p>
  
  <p>I am using Ubuntu Linux 12.04.</p>
  
  <p>Thanks in advance for your help.</p>