如何使用PyO3解组PyCodeObject?

2024-05-16 01:12:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读.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());
}

要创建测试文件,请执行以下操作:

  1. 创建一个.py文件
  2. 用Python导入模块(例如python(3) -c 'import ...'
  3. __pycache__文件夹中应该有一个.pyc文件
  4. 用实际路径替换对include_bytes!的调用中代码中的路径

版本信息

  • Rust 2018
  • rustc 1.43.0-每晚(564758c4c 2020-03-08)
  • 货运1.43.0-每晚(bda50510d 2020-03-02)
  • CPython 3.7.3
  • PyO3 0.9.1

Tags: 文件ofthepyforisbuffernot
1条回答
网友
1楼 · 发布于 2024-05-16 01:12:44

我想我已经想出了如何做到这一点:

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 };

相关问题 更多 >