繁体   English   中英

如何将指向 Rust 结构的参考/指针传递给 C ffi 接口?

[英]How to pass a Reference / Pointer to a Rust Struct to a C ffi interface?

我想要做什么

我已经构建了一个 Rust 接口,我想通过 C (或 C# 进行交互,但这并不重要)。 Because it does not seem to be possible to make a Rust Struct accessible to C I am trying to build some wrapper functions that I can call and that will create the Struct in Rust, call functions of the struct and eventually free the Struct from memory manually .

为了做到这一点,我想我会将指向我在init function 中创建的 Struct 实例的指针传递回 C(或IntPtr )并将其临时存储为 IntP。 然后,当我调用其他函数时,我会再次将指针传递给 Rust,取消引用它并在取消引用的 Struct 上调用适当的函数,在此过程中对其进行变异。

我知道我将不得不使用不安全的代码来执行此操作,我对此很好。 我可能还应该指出,我对 Rust 中的生命周期管理知之甚少,而且很可能,我试图做的事情是不可能的,因为在某处很容易产生松散的指针。 在这种情况下,我想知道我需要如何调整我的方法,因为我认为我不是第一个试图从 ZF5E265D607CB720058FC166FEZ008 中的 C 变异某种state的人。

我首先尝试的

所以首先我确保 output 正确的库并向其中添加我的本机函数。 Cargo.toml 中,我将 lib 类型设置为:

[lib]
crate-type = ["cdylib"]

然后我创建了一些函数来与结构交互并像这样公开它们:

#[no_mangle]
pub extern fn init() -> *mut MyStruct {
    let mut struct_instance = MyStruct::default();
    struct_instance.init();
    let raw_pointer_mut = &mut struct_instance as *mut MyStruct;
    return raw_pointer_mut;
}

#[no_mangle]
pub extern fn add_item(struct_instance_ref: *mut MyStruct) {
    unsafe {
        let struct_instance = &mut *struct_instance_ref;

        struct_instance.add_item();
    }
}

正如您在init function 中看到的那样,我正在创建结构,然后返回(可变)指针。

然后我在add_item function 中取出指针并使用它。

现在我尝试测试这个实现,因为我对指针仍然有效有一些疑问。 在另一个 Rust 模块中,我加载了 .dll 和 .lib 文件(我在 Windows 上,但这对问题无关紧要)然后相应地调用函数,如下所示:

fn main() {
    unsafe {
        let struct_pointer = init();
        add_item(struct_pointer);
        println!("The pointer adress: {:?}", struct_pointer);
    }
}

#[link(name = "my_library.dll")]
extern {
    fn init() -> *mut u32;
    fn add_item(struct_ref: *mut u32);
}

发生了什么:我确实得到了一些 memory 地址 output 并且(因为我实际上是在实际实现中创建一个文件)我还可以看到这些功能按计划执行。 然而,Struct 的字段似乎没有发生突变。 它们基本上都是空的,在我调用add_item function 之后它们不应该是空的(在我调用init函数之后也不应该)。

之后我尝试了什么

我在 Rust 中阅读了一些关于生命周期管理的内容,因此尝试使用这样的Box堆上分配 Struct:

#[no_mangle]
pub extern fn init() -> *mut Box<MyStruct> {
    let mut struct_instance = MyStruct::default();
    struct_instance.init();
    let raw_pointer_mut = &mut Box::new(struct_instance) as *mut Box<MyStruct>;
    return raw_pointer_mut;
}

#[no_mangle]
pub extern fn add_box(struct_instance_ref: *mut Box<MyStruct>) {
    unsafe {
        let struct_instance = &mut *struct_instance_ref;

        struct_instance.add_box();
    }
}

不幸的是,结果与上述相同。

附加信息

我认为还包括原则上如何构成Struct可能会很好:

#[derive(Default)]
#[repr(C)]
pub struct MyStruct{
    // Some fields...
}

impl MyStruct{
    /// Initializes a new struct.
    pub fn init(&mut self) {
        self.some_field = whatever;
    }

    /// Adds an item to the struct.
    pub fn add_item(
        &mut self,
        maybe_more_data: of_type // Obviously the call in the external function would need to be adjusted to accomodate for that...
    ){
        some_other_function(self); // Calls another function in Rust, that will take the struct instance as an argument and mutate it.
    }
}

Rust 具有强烈的所有权概念。 问问自己:谁拥有MyStruct实例? 它是struct_instance变量,它的生命周期是init() function 的 scope。 所以在init()返回后,实例被删除并返回一个无效的指针。

在堆上分配MyStruct将是解决方案,但不是您尝试的方式:实例被移动到堆中,但随后Box包装器绑定到相同的有问题的生命周期,因此它破坏了堆分配的 object。

一个解决方案是使用Box::into_raw在盒子被丢弃之前将堆分配的值从盒子中取出:

#[no_mangle]
pub extern fn init() -> *mut MyStruct {
    let mut struct_instance = MyStruct::default();
    struct_instance.init();
    let box = Box::i(struct_instance);
    Box::into_raw(box)
}

要稍后销毁该值,请使用Box::from_raw创建一个拥有它的新Box ,然后让该框在其离开 scope 时释放其包含的值:

#[no_mangle]
pub extern fn destroy(struct_instance: *mut MyStruct) {
    unsafe { Box::from_raw(struct_instance); }
}

这似乎是一个常见问题,因此可能有更惯用的解决方案。 希望有经验的大侠指点一下。

我正在为遇到此问题但不需要装箱的任何人添加一个简单的答案 - &mut struct_instance as *mut _是获取指向堆栈上结构的可变指针的正确语法。 这种语法在任何地方都很难找到文档,很容易错过最初的mut

值得注意的是,这并不能解决原始发布者的问题,因为返回指向本地的指针是未定义的行为。 但是,这是通过 FFI 调用某些东西的正确解决方案(Google 上似乎没有更好的结果)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM