问题
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