python - 如何使用 PyO3 解组 PyCodeObject?
问题描述
我正在阅读 .pyc 文件,并且需要能够解组代码对象。当我尝试将未编组的内容向下转换PyAny
为 时PyCodeObject
,我收到以下错误消息:
error[E0277]: the trait bound `pyo3::ffi::code::PyCodeObject: pyo3::type_object::PyTypeInfo` is not satisfied
--> src/lib.rs:179:47
|
179 | let code = *(loads(py, &code_buffer)?.downcast::<PyCodeObject>()?);
| ^^^^^^^^ the trait `pyo3::type_object::PyTypeInfo` is not implemented for `pyo3::ffi::code::PyCodeObject`
|
= note: required because of the requirements on the impl of `for<'py> pyo3::conversion::PyTryFrom<'py>` for `pyo3::ffi::code::PyCodeObject`
error[E0277]: the trait bound `pyo3::ffi::code::PyCodeObject: pyo3::instance::PyNativeType` is not satisfied
--> src/lib.rs:179:47
|
179 | let code = *(loads(py, &code_buffer)?.downcast::<PyCodeObject>()?);
| ^^^^^^^^ the trait `pyo3::instance::PyNativeType` is not implemented for `pyo3::ffi::code::PyCodeObject`
|
= note: required because of the requirements on the impl of `for<'py> pyo3::conversion::PyTryFrom<'py>` for `pyo3::ffi::code::PyCodeObject`
这样做的正确方法是什么?
MCVE
use pyo3::{ffi::PyCodeObject, marshal::loads, Python};
fn main() {
let gil_guard = Python::acquire_gil();
let py = gil_guard.python();
let code_buffer = &include_bytes!("__pycache__/test.cpython-37.pyc")[16..];
let code = *(loads(py, &code_buffer)
.unwrap()
.downcast::<PyCodeObject>()
.unwrap());
}
创建测试文件:
- 创建一个 .py 文件
- 在 Python 中导入模块(例如
python(3) -c 'import ...'
) __pycache__
文件夹中应该有一个 .pyc 文件- 将调用中代码中的路径替换为
include_bytes!
实际路径
版本信息
- 生锈 2018
- rustc 1.43.0-nightly (564758c4c 2020-03-08)
- 货物 1.43.0-nightly (bda50510d 2020-03-02)
- CPython 3.7.3
- PyO3 0.9.1
解决方案
我想我已经想出了如何做到这一点:
let code_ptr = loads(py, &code_buffer)?.as_ptr() as *mut PyCodeObject;
// This should be valid, since PyCodeObject is Copy, as long as the refcount is positive
let code = unsafe { *code_ptr };
推荐阅读
- python - Numpy 在读取 CSV 时将科学记数法转换为 nan
- bazel - Bazel 文件名中带有“:”的解决方法?
- powershell - Powershell 杀死除当前打开的所有 Powershell 窗口
- c++ - 如何从rabbitmq的库中的消息中读取reply_to - amqpcpp?
- microsoft-graph-api - Microsoft Graph 更新订阅总是导致 403 Forbidden 错误
- visual-studio - 在 Visual Studio 2017 安装程序中修改用户和系统变量
- angular - 角度自定义管道返回表数据错误
- java - Java - 每次循环迭代后累加器变量不递增
- stylesheet - Drupal 8 样式表更改每次都必须重建缓存。有没有更好的办法?
- sql - 如何在 SQL Server 中创建数据集并处理每条记录?