如何用Rust封装现有的C函数或如何从Rust调用C函数

如何用Rust封装现有的C函数或如何从Rust调用C函数

本文介绍了如何用Rust封装现有的C函数或如何从Rust调用C函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有现有的C代码及其标头,我需要从Rust调用C代码.我尝试了很多方法并参考了文档,但我不知道如何将其应用于代码.我面临着将C函数转换为Rust的困难.请帮我举一些例子,以便我容易理解.

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.

我尝试使用Rust书中给出的示例以及其他网站示例,但是没有资源对此提供更多详细信息.

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);

我想在Rust中调用上述所有函数,但是我无法理解如何启动或更改.包装此C代码时,我们需要注意什么?有哪些可用的方法?

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?

推荐答案

如果您尝试从Rust调用C代码,则需要创建FFI绑定,就像某些人在评论中提到的那样.

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

但是,通常最好通过 rust-bindgen ,它会自动生成绑定并包括测试以确保结果的大小正确,对齐等.创建大小错误的类型非常容易,这在编译时不会给您任何警告,并且可以导致不确定的行为,除非您使用bindgen为它们生成测试.

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.

这篇关于如何用Rust封装现有的C函数或如何从Rust调用C函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-21 02:37