来自 C++ 的函数没有接收到在 Rust 中调用的正确参数

问题描述 投票:0回答:0

我正在尝试将 *.cc 链接到 rust 中。

build.rs:

fn main() {
    cc::Build::new()
        .file("src/bindings.cc")
        .cargo_metadata(true)
        .cpp(true)
        .compile("bindings");
}

绑定.cc:

extern "C" {
    leveldb::Status db_get(
        LevelDB* db,
        const char* key, size_t keylen,
        const char** val, size_t* vallen,
        bool fillCache
    ) {
        printf("0: %p, 1: %p, 2: %d, 3: %p, 4: %p, 5: %s\n",
            db,
            key, keylen,
            val, vallen,
            fillCache ? "true" : "false"
        );
        leveldb::Status status;
        return status;
    }
}

sys.rs:

#[link(name="bindings")]
extern "c" {
    pub fn db_get(
        db: *mut LevelDB,
        key: *const u8, keylen: usize,
        val: *mut *const u8, vallen: *mut usize,
        fill_cache: bool
    ) -> Status;
}

我这样称呼它:

println!("0: {:?}, 1: {:?}, 2: {:?}, 3: {:?}, 4: {:?}, 5: {}",
    self.raw.as_ptr(),
    key.as_ptr(), key.len(),
    &mut val, &mut len,
    options.fill_cache
);

let status = sys::db_get(
    self.raw.as_ptr(),
    key.as_ptr(), key.len(),
    &mut val, &mut len,
    options.fill_cache
);

现在,当我运行它时,它会打印:

0: 0x58aa2fc8a700, 1: 0x58aa2fc8a6e0, 2: 9, 3: 0x0, 4: 0, 5: true
0: 0x58aa2fc8a6e0, 1: 0x9, 2: 1439424216, 3: 0x7fff55cbdee0, 4: 0x1, 5: true

每次运行时指针可能不同,但它仍然相同,与我打算在 rust 代码中提供的内容不一致。我向你保证,我计算了外部函数参数类型的大小,并确保它们在生锈方面是相等的,对于返回类型也是如此。仅从观察来看,我可以看到参数向左移动。我无法查明问题

c++ rust ffi extern
© www.soinside.com 2019 - 2024. All rights reserved.