title: How to fix "Access Violation" error when returning PyObject from C function using PyTCC library
body: <p>I am using a Python library that wraps LibTCC called <a href="https://github.com/frxstrem/pytcc" rel="nofollow noreferrer">PyTCC</a>.</p>
  
  <p>I am experimenting with ways to JIT compile code in Python. Problem is, when calling a function I can return normal C data types correctly but I get an "Access Violation" error when returning any <code>PyObject *</code>.</p>
  
  <p>I have made sure that code can execute from PyTCC as my code example shows.  This also means that the code example is compiling successfully.</p>
  
  <pre class="lang-py prettyprint-override"><code>import ctypes, pytcc
  
  program = b"""
  #include "Python.h"
  
  /* Cannot return 3 due to access violation */
  PyObject * pop(PyObject * self, PyObject * args, PyObject * kwargs) {
      // Cannot return *any* Python object
      return PyLong_FromLong(3);
  }
  
  int foobar() { return 3; }  // Returns 3 just fine
  
  // Needed to appease TCC:
  int main() { }
  """
  
  jit_code = pytcc.TCCState()
  jit_code.add_include_path('C:/Python37/include')
  jit_code.add_library_path('C:/Python37')
  jit_code.add_library('python37')
  jit_code.compile_string(program)
  jit_code.relocate()
  
  foobar_proto = ctypes.CFUNCTYPE(ctypes.c_int)
  foobar = foobar_proto(jit_code.get_symbol('foobar'))
  
  print(f'It works: {foobar()}')
  
  pop_proto = ctypes.CFUNCTYPE(ctypes.c_voidp)
  pop = pop_proto(jit_code.get_symbol('pop'))
  
  print('But this does not for some reason:')
  print(pop())
  print('Never gets here due to access violation :(')
  </code></pre>
  
  <p>The output of the program should be:</p>
  
  <pre><code>It works: 3
  But this does not for some reason:
  3
  Never gets here due to access violation :(
  </code></pre>
  
  <p>But instead, I am getting this exact error:</p>
  
  <pre><code>It works: 3
  But this does not for some reason:
  Traceback (most recent call last):
    File "fails.py", line 40, in &lt;module&gt;
      print(pop())
  OSError: exception: access violation writing 0x00000000FFC000E9
  </code></pre>