0
#[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"]
4

1 回答 1

0

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

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

请参阅PyErr了解导致 Python 错误的几种方法。

于 2021-11-29T00:19:37.643 回答