How to wrap existing C functions with Rust or how to call C functions from Rust?

送分小仙女□ 提交于 2020-01-16 08:43:13

问题


I have existing C code and its header and I need to call the C code from Rust. I tried it many ways and referred to documents but I didn't understand how to apply that to my code. I'm facing difficulties converting C functions into Rust. Please help me with some examples so that I can understand easily.

I tried to use the examples given in the Rust book and other website examples, but no resource has more details on this.

C_code.h

void ifx_vec_init_r(ifx_Vector_R_t* vector,
                    ifx_Float_t* d,
                    uint32_t length);

void ifx_vec_init_c(ifx_Vector_C_t* vector,
                    ifx_Complex_t* d,
                    uint32_t length);

void ifx_vec_rawview_r(ifx_Vector_R_t* vector,
                       ifx_Float_t* d,
                       uint32_t length,
                       uint32_t stride);

void ifx_vec_sub_r(const ifx_Vector_R_t* v1,
                   const ifx_Vector_R_t* v2,
                   ifx_Vector_R_t* result);

I want to call all above functions in Rust, but I am not able to understand how to start or how to change. What and all we to take care to wrap this C code? What are the ways available?


回答1:


If you're trying to call C code from Rust, you need to create FFI bindings as some people have mentioned in the comments.

However, it is usually best to do this via rust-bindgen, which automatically generates the bindings and includes tests to make sure that the results are properly sized, aligned, etc. It is very easy to create a type with an incorrect size, which will give you no warning at compile-time and can cause undefined behavior unless you generate tests for them with bindgen.



来源:https://stackoverflow.com/questions/58708760/how-to-wrap-existing-c-functions-with-rust-or-how-to-call-c-functions-from-rust

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