I have some python bytecode file as "a.pyc","b.pyc".I want to run this file in c++ code. The code can call boost.python or python/c api. PyEval_EvalCode?
PyObject* PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
But how to get PyCodeObject from the bytecode file.
As far as I know, you can't do this from the Very High Level layer. (Have you tried PyRun_SimpleFileExFlags?) So you want to look at the Importing Modules API.
If you're just trying to import foo, or do the equivalent importlib-ish stuff, without caring whether it's foo.py or foo.pyc, that's not too hard. But if you're trying to avoid the usual rules for import and explicitly specify the file by pathname… that must be possible, but I can't think of any way to do that… except:
A .pyc file is, under the covers, just the magic number from PyImport_GetMagicNumber(), then a 4-byte timestamp which you can ignore, then a marshalled code object, which you can marshal.loads from Python or PyMarshal_ReadObjectFromString from C.
I haven't tested this from C, but from Python:
>>> with open('foo.pyc', 'rb') as f:
... data = f.read()
>>> code = marshal.loads(data[8:])
>>> code
<code object <module> at 0x110118730, file "foo.py", line 1>
And examining it, it seems to be exactly what it ought to be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With