PyO3 built rust binding executable gives import error?

722 views Asked by At

I recently came across PyO3 and I have successfully built the example code from PyO3 repo.

Cargo.toml

[package]
name = "string-sum"
version = "0.1.0"
edition = "2018"

[lib]
name = "string_sum"
crate-type = ["cdylib"]

[dependencies.pyo3]
version = "0.12.1"
features = ["extension-module"]

lib.rs

use pyo3::prelude::*;
use pyo3::wrap_pyfunction;

/// Formats the sum of two numbers as string.
#[pyfunction]
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
    Ok((a + b).to_string())
}

/// A Python module implemented in Rust.
#[pymodule]
fn string_sum(py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;

    Ok(())
}

The build created two files libstring_sum.d and libstring_sum.so, then I created a test python script and tried to build this rust binding using import libstring_sum but it gives this error

ImportError: dynamic module does not define module export function (PyInit_libstring_sum)

1

There are 1 answers

0
Eka On

It is working now, this is what I did,

I copied the libstring_sum.so to different directory and renamed it to string_sum.so, then I wrote the python script and imported it using import string_sum.

After that you can do string_sum.sum_as_string(10,20) and this worked.