首页 > 解决方案 > 如何在 c python api 中从 PyCodeObject 获取源代码?

问题描述

嗨,我正在使用 c python api。我想提取函数对象的源代码。我想要纯 python 代码(比如 def func: ... )但是如果很难的话,我至少想得到 py 字节码。

这是我从 PyFunctionObject 获取 PyCodeObject 的 c++ 代码。

//pObject is PyFunctionObject which is python standard lib's function.
PyFunctionObject* pFunctionObject = (PyFunctionObject*)pObject;

PyCodeObject* codeObject = (PyCodeObject*)pFunctionObject->func_code;

PyObject* strObject = codeObject->co_code; //get code from code object

char * sourceCode = PyString_AsString(strObject); //convert to string

但是 sourceCode 变量(char*)总是只显示 1 个字节。

我该怎么得到这个?在 python 代码方面有很多方法可以做到这一点,比如只使用 'dis' 或 'inspect' 模块。但我想通过 c python api 做到这一点。

PS 我猜 PyCodeObject 的 co_code 成员是一个字节数组。我使用了 Visual Studio 调试内存视图并看到了 co_code 成员的相邻内存字节,但它看起来像是一个字节码数组(可能只是)。

标签: c++cpython

解决方案


首先,PyCodeObject->co_code是生成的字节码,而不是纯 Python 源代码。

在 Python 中,我们可以inspect.getsource用来获取纯 Python 源代码。在 C 中,你也可以通过PyObject_CallMethod


推荐阅读