【问题标题】:Compiling rust to python library, error not implemented. How to compile rust library with error into python module将 rust 编译到 python 库,错误未实现。如何将带有错误的 rust 库编译到 python 模块中
【发布时间】:2021-11-28 22:36:18
【问题描述】:
#[macro_use]
extern crate cpython;

use cpython::{Python, PyResult};

// file: main.rs
use concrete::*;

fn get_cypher(_py: Python, val: &f64) -> PyResult<()> {
    // generate a secret key
    let secret_key = LWESecretKey::new(&LWE128_1024);
    // encoder
    let encoder = Encoder::new(100., 210., 8, 0)?;

    // encode and encrypt
    let message = 106.276;
    let mut ciphertext = LWE::encode_encrypt(&secret_key, message, &encoder)?;

    // addition between ciphertext and a constant
    let constant = 102.0;
    ciphertext.add_constant_static_encoder_inplace(constant)?;
    
    // decryption
    let output = ciphertext.decrypt_decode(&secret_key)?;
    println!("{} + {} = {}", message, constant, output);
    Ok(())
}

py_module_initializer!(libmyrustlib, initlibmyrustlib, PyInit_myrustlib, |py, m | {
    (m.add(py, "__doc__", "This module is implemented in Rust"))?;
    (m.add(py, "get_cypher", py_fn!(py, get_cypher(val: &f64))))?;
    Ok(())
});

所以,我正在尝试编译这个 rust 代码以便能够在 python 中调用它,但是我收到以下错误:

    9   | fn get_cypher(_py: Python, val: &f64) -> PyResult<()> {
    |                                          ------------ expected `PyErr` because of this
...
24  |     let output = ciphertext.decrypt_decode(&secret_key)?;
    |                                                        ^ the trait `From<CryptoAPIError>` is not implemented for `PyErr`

如何将 rust 中的错误传递给 python,以便编译这段代码?我想一般来说,当一个 rust 库实现错误时,我怎样才能确保我仍然可以使用该库编译代码?

货物文件:

[package]
name = "fhe_play"
version = "0.1.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
concrete = "0.1.0"
itertools = "0.9.0"

[dependencies.cpython]
version = "0.1"
features = ["extension-module"]

【问题讨论】:

    标签: python rust compilation cryptography fhe


    【解决方案1】:

    如果尚未定义转换,您需要手动从一种错误类型转换为另一种错误类型。您可以使用.map_err() 执行此操作。这是一个例子:

    let output = ciphertext
        .decrypt_decode(&secret_key)
        .map_err(|_original_error| {
            PyErr::new::<Exception, _>(_py, "some error value")
        })?;
    

    请参阅PyErr 了解一些导致 Python 错误的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多