【问题标题】:Error when calling Rust from Python从 Python 调用 Rust 时出错
【发布时间】:2015-09-19 10:34:52
【问题描述】:

锈代码:

#[no_mangle]
use std::thread;

pub extern fn process() {
    let handles: Vec<_> = (0..10).map(|_| {
        thread::spawn(|| {
            let mut _x = 0;
            for _ in (0..5_000_001) {
                _x += 1
            }
        })
    }).collect();

    for h in handles {
        h.join().ok().expect("Could not join a thread!");
    }
}

Cargo.toml:

[package]
name = "embed"
version = "0.1.0"
authors = ["hustlibraco <hustlibraco@gmail.com>"]

[lib]
name = "embed"
crate-type = ["dylib"]

我构建它是为了得到target/release/libembed.so,并在这个路径下创建invoke.py

from ctypes import cdll

lib = cdll.LoadLibrary("target/release/libembed.so")

lib.process()

print("done!")

执行,报错:

-bash-4.2# python invoke.py 
Traceback (most recent call last):
  File "invoke.py", line 5, in <module>
    lib.process()
  File "/usr/lib64/python2.7/ctypes/__init__.py", line 373, in __getattr__
    func = self.__getitem__(name)
  File "/usr/lib64/python2.7/ctypes/__init__.py", line 378, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: target/release/libembed.so: undefined symbol: process

如何解决这个问题?

【问题讨论】:

    标签: python rust shared-libraries ctypes


    【解决方案1】:

    #[no_mangle] 继续函数,而不是use

    #[no_mangle]
    pub extern fn process() { ... }
    

    有关完整的工作示例,请参阅the Rust FFI Omnibus "Integers" example

    【讨论】:

      猜你喜欢
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      相关资源
      最近更新 更多