Rust 调用C/C++

作者: 疯狂的冰块 | 来源:发表于2018-05-27 16:49 被阅读111次

    需要引入cc依赖

    Cargo.toml

    [package]
    name = "rust-call-c"
    version = "0.1.0"
    authors = ["ice <bsqql123@163.com>"]
    
    build = "build.rs"
    
    [dependencies]
    libc = "0.2"
    
    [build-dependencies]
    cc = "1.0"
    

    build.rs

    extern crate cc;
    
    fn main() {
        cc::Build::new()
            .file("src/double.c")
            .compile("libdouble.a");
    }
    

    main.rs

    extern crate libc;
    
    extern {
        fn double_input(input: libc::c_int) -> libc::c_int;
    }
    
    //TODO
    fn main() {
        let input = 4;
        let output = unsafe { double_input(input) };
        println!("{} * 2 = {}", input, output);
    }
    

    double.c

    int double_input(int input) {
        return input * 2;
    }
    

    具体例子在
    https://github.com/iceqing/rust-call-c

    这里是一个比较完整的例子,有各种语言的示例代码
    https://github.com/iceqing/rust-ffi-examples

    相关文章

      网友评论

        本文标题:Rust 调用C/C++

        本文链接:https://www.haomeiwen.com/subject/eqabjftx.html