How to call C function in Rust

徘徊边缘 提交于 2020-04-18 05:54:04

问题


I'm a C programmer and I'm trying to call Rust function in my application and the rust function also need call C functions which exist at my application.

I know that if I want call C function in Rust I have to do like this

#[link(name = "mylib")]
extern "C" {
    pub fn c_function();
}

But the c_function doesn't exist in any lib but only in my application env now.

For example: My C code is

void c_function()
{
    return 1;
}

void main()
{
    rust_function();
}

My Rust code is(cargo new --lib myrustlib)

pub unsafe extern "C" fn  rust_function() {
    //If I want to call c_function which is in C world here, How could I do this?
    //I have tried using extern "C" {pub fn c_function();} but faild.  
    //And an error is outputted like this "undefined reference to `c_function'"
}


回答1:


You're on the right track. You can auto-generate C header from the Rust program with cbindgen, and the other way, Rust bindings with bindgen.

Add crate-type = ["lib", "staticlib", "cdylib"] to Cargo.toml to generate .a and .so/.dylib/.dll versions of the Rust library that you can link with the C program.



来源:https://stackoverflow.com/questions/57353387/how-to-call-c-function-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!