gpt4 book ai didi

c - 将 Rust 指针传递给 C 时,我应该得到 0x1 吗?

转载 作者:太空宇宙 更新时间:2023-11-04 00:44:42 24 4
gpt4 key购买 nike

我正在尝试在 Rust 中实现一个基本库,它创建一个对象并将其指针返回给 C。我得到的指针看起来不像在堆上——当我打印它时,我得到 0x1 :

use std::fmt;

pub struct SndbDB {}

impl SndbDB {
fn new() -> SndbDB {
SndbDB {}
}
}

impl fmt::Display for SndbDB {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(sndb_db)")
}
}

// Implement a destructor just so we can see when the object is destroyed.
impl Drop for SndbDB {
fn drop(&mut self) {
println!("[rust] dropping {}", self);
}
}

#[no_mangle]
pub extern "C" fn sndb_db_create() -> *mut SndbDB {
let _db = Box::into_raw(Box::new(SndbDB::new()));
println!("[rust] creating DB {:?}", _db);
_db
}

#[no_mangle]
pub unsafe extern "C" fn sndb_db_destroy(ptr: *mut SndbDB) {
println!("[rust] destroying DB {:?}", ptr);
Box::from_raw(ptr); // Rust drops this for us.
}

C 调用代码也很简单:

typedef struct sndb_db sndb_db;

sndb_db * sndb_db_create(void);
void sndb_db_destroy(sndb_db* db);

void test_baseapi__create_and_destroy_db(void)
{
sndb_db * db = sndb_db_create();
printf("[C] Got db=%p\n",db);
sndb_db_destroy(db);
printf("[C] db should be dead by now...\n");
}

除指针位置外的所有输出都如我所料:

[rust] creating DB 0x1
[C] Got db=0x1
[rust] destroying DB 0x1
[rust] dropping (sndb_db)
[C] db should be dead by now...

我知道在 Rust 中分配的内存需要由 Rust 释放 - 但我仍然很惊讶它使用的是 0x1 的位置 - 我做错了什么,发生了什么奇怪的事情,或者这一切都好吗?

最佳答案

看起来这是 Rust 的优化,因为 SndbDB 结构没有状态。

向其添加一个 i: u32 字段并将其连接到构造函数和 C 代码,然后我得到:

[rust] creating DB 0x7fff2fe00000
[C] Got db=0x7fff2fe00000
[rust] destroying DB 0x7fff2fe00000
[rust] dropping (sndb_db i=123)
[C] db should be dead by now...

但是我仍然很想找到一个官方来源来支持这个猜测。

关于c - 将 Rust 指针传递给 C 时,我应该得到 0x1 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47483112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com