我如何使用PyO3解组PyCodeObject?

问题描述 投票:0回答:1

我正在读取.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};

let gil_guard = Python::acquire_gil();
let py = gil_guard.python();
// Taken from a .pyc file for an empty .py file, Python 3.7
let code_buffer = [
    0xe3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
    0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x73, 0x04, 0x00, 0x00, 0x00, 0x64, 0x00, 0x53, 0x00,
    0x29, 0x01, 0x4e, 0xa9, 0x00, 0x72, 0x01, 0x00, 0x00, 0x00, 0x72, 0x01, 0x00, 0x00, 0x00,
    0x72, 0x01, 0x00, 0x00, 0x00, 0xfa, 0x53, 0x2f, 0x68, 0x6f, 0x6d, 0x65, 0x2f, 0x73, 0x6f,
    0x6c, 0x6c, 0x79, 0x2f, 0x44, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x43,
    0x6f, 0x64, 0x65, 0x2f, 0x52, 0x75, 0x73, 0x74, 0x2f, 0x72, 0x65, 0x76, 0x2d, 0x73, 0x74,
    0x75, 0x64, 0x69, 0x6f, 0x2f, 0x6c, 0x61, 0x6e, 0x67, 0x73, 0x2f, 0x72, 0x65, 0x76, 0x2d,
    0x73, 0x74, 0x75, 0x64, 0x69, 0x6f, 0x2d, 0x70, 0x79, 0x74, 0x68, 0x6f, 0x6e, 0x2f, 0x74,
    0x65, 0x73, 0x74, 0x5f, 0x72, 0x65, 0x73, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x70, 0x79,
    0xda, 0x08, 0x3c, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x3e, 0x01, 0x00, 0x00, 0x00, 0xf3,
    0x00, 0x00, 0x00, 0x00,
];
let code = *(loads(py, &code_buffer)?.downcast::<PyCodeObject>()?);
python rust unmarshalling ffi pyo3
1个回答
0
投票

我想我已经知道如何做到这一点:

let code_ptr = loads(py, &code_buffer)?.as_ptr() as *mut PyCodeObject;
let code = unsafe { *code_ptr }; // I hope this is valid...
© www.soinside.com 2019 - 2024. All rights reserved.