I am using a Python library that wraps LibTCC called PyTCC.
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 PyObject *
.
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.
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 :(')
The output of the program should be:
It works: 3
But this does not for some reason:
3
Never gets here due to access violation :(
But instead, I am getting this exact error:
It works: 3
But this does not for some reason:
Traceback (most recent call last):
File "fails.py", line 40, in <module>
print(pop())
OSError: exception: access violation writing 0x00000000FFC000E9