如何在 Rust 中创建等效的 C 双指针? [英] How do I make the equivalent of a C double pointer in Rust?

查看:63
本文介绍了如何在 Rust 中创建等效的 C 双指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始将 C 代码移植到 Rust,但我对 Rust 中的工作方式感到困惑.这段代码的等价物是什么:

typedef struct Room {int xPos;内部位置;} 房间;无效主(){房间**房间;房间 = malloc(sizeof(Room)*8);}

解决方案

这段代码的等价物是什么

假设您的意思是一组 Room,容量为 8":

struct Room {x_pos: i32,y_pos: i32,}fn 主(){出租房间:Vec= Vec::with_capacity(8);}

在 Rust 中直接调用分配器是极其罕见的.一般来说,你有一个为你做这件事的集合.您通常也不会明确指定集合的​​项目类型,因为它可以通过您放入的内容推断出来,但是由于您的代码根本不使用 rooms,我们必须通知编译器.

正如评论中指出的,您不需要双指针.这相当于 Room *.如果你真的想要一个额外的间接级别,你可以添加 Box:

出租房间:Vec>= Vec::with_capacity(8);

<块引用>

如何制作等效于 C 的双指针

Rust 与 C 的优势之一是,在 C 中,您不知道 foo_t ** 的语义.谁应该释放每个指针?哪些指针是可变的?您可以在 Rust 中创建原始指针,但即使这样也需要指定可变性.这几乎不是您想要的:

出租房间:*mut *mut Room;

在某些 FFI 情况下,C 函数接受 foo_t ** 因为它想要修改传入的指针.在这些情况下,这样的事情是合理的:

不安全{让 mut 房间:*mut Room = std::ptr::null_mut();let room_ptr: *mut *mut Room = &mut room;}

I started porting C code to Rust, but I'm confused about how things work in Rust. What is the equivalent of this code:

typedef struct Room {
    int xPos;
    int yPos;
} Room;

void main (){
  Room **rooms;
  rooms = malloc(sizeof(Room)*8);
}

解决方案

What is the equivalent of this code

Assuming you mean "a collection of Rooms with capacity for 8":

struct Room {
    x_pos: i32,
    y_pos: i32,
}

fn main() {
    let rooms: Vec<Room> = Vec::with_capacity(8);
}

It's exceedingly rare to call the allocator directly in Rust. Generally, you have a collection that does that for you. You also don't usually explicitly specify the item type of the collection because it can be inferred by what you put in it, but since your code doesn't use rooms at all, we have to inform the compiler.

As pointed out in the comments, you don't need a double pointer. This is the equivalent of a Room *. If you really wanted an additional level of indirection, you could add Box:

let rooms: Vec<Box<Room>> = Vec::with_capacity(8);

How do I make the equivalent of a C double pointer

One of the benefits of Rust vs C is that in C, you don't know the semantics of a foo_t **. Who should free each of the pointers? Which pointers are mutable? You can create raw pointers in Rust, but even that requires specifying mutability. This is almost never what you want:

let rooms: *mut *mut Room;

In certain FFI cases, a C function accepts a foo_t ** because it wants to modify a passed-in pointer. In those cases, something like this is reasonable:

unsafe {
    let mut room: *mut Room = std::ptr::null_mut();
    let room_ptr: *mut *mut Room = &mut room;
}

这篇关于如何在 Rust 中创建等效的 C 双指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆