c++ - 如何在 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 成员的相邻内存字节,但它看起来像是一个字节码数组(可能只是)。
解决方案
首先,PyCodeObject->co_code
是生成的字节码,而不是纯 Python 源代码。
在 Python 中,我们可以inspect.getsource
用来获取纯 Python 源代码。在 C 中,你也可以通过PyObject_CallMethod
推荐阅读
- in-app-purchase - ios中的inApp购买支付
- android - 在android webview中手动触发剪切/复制/粘贴
- git - 删除旧的提交,只在远程上保留最新的提交
- cucumber-java - 没有找到后端
- javascript - 在由 JS/PHP Ajax 请求生成的数组中传递 0 的问题
- mysql - 这个获取年销售额(收入)的 SQL 语句是否正确?
- java - 使用 Spring Data JPA 执行“INSERT ... ON DUPLICATE KEY UPDATE”的最佳方法?
- c# - ExecuteNonQuery 不更新输出参数
- c# - 有一个函数参数作为 Action 是否常见
而不是只有 T,为什么? - sql - 记录集。在同一记录的其他列中查找并返回值