我正在使用一个名为PyTCC的包装 LibTCC 的 Python 库。
我正在尝试在 Python 中 JIT 编译代码的方法。问题是,在调用函数时,我可以正确返回正常的 C 数据类型,但在返回任何PyObject *
.
正如我的代码示例所示,我已确保代码可以从 PyTCC 执行。这也意味着代码示例正在编译成功。
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 :(')
程序的输出应该是:
It works: 3
But this does not for some reason:
3
Never gets here due to access violation :(
但相反,我得到了这个确切的错误:
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