代码之家  ›  专栏  ›  技术社区  ›  PPP

如何在C++代码中锈蚀代码中保存锈蚀对象

  •  0
  • PPP  · 技术社区  · 5 年前

    为了实现这一点,我需要一种方法来将实例存储在某种列表中,并将列表的索引返回到C++,这样它就可以像一个指向锈结构的指针。

    Rust不支持静态成员,因此无法创建 static rust_instances: std::vec::Vec = std::vec::Vec::new() 以保持生锈的结构。

    我已经搜索并找到了一些模拟静态元素的解决方法,但是我想知道是否有更好的方法来解决这个问题。

    0 回复  |  直到 5 年前
        1
  •  2
  •   Sven Marnach    5 年前

    要实现这一点,我们需要一种方法将实例存储到某种列表中,并将列表的索引返回到C++,因此它像一个指向锈结构的指针。

    Box 在鲁斯特中,并将其返回到C++代码A Box<T> T: Sized the same memory layout as a C pointer

    如链接文档中所述,您的代码可以简单地如下所示:

    // C++ header
    
    // Returns ownership to the caller
    extern "C" void *foo_new();
    
    // Borrows mutably. The pointee cannot be changed by a different thread
    // during the runtime of the function. The argument must be a pointer
    // allocated with foo_new().
    extern "C" void foo_transmogrify(void *);
    
    // Takes ownership from the caller; no-op when invoked with NULL
    extern "C" void foo_delete(void *);
    
    #[repr(C)]
    pub struct Foo {
        glonk: bool,
    }
    
    #[no_mangle]
    pub extern "C" fn foo_new() -> Box<Foo> {
        Box::new(Foo { glonk: false })
    }
    
    #[no_mangle]
    pub extern "C" fn foo_transmogrify(foo: &mut Foo) {
        foo.glonk = true;
    }
    
    #[no_mangle]
    pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
    

    注意,deallocation函数可以是空的。它将拥有 盒子

    推荐文章