gpt4 book ai didi

c++ - 分配内存并调用 C++ 回调的 Rust 函数崩溃

转载 作者:搜寻专家 更新时间:2023-10-31 00:27:09 24 4
gpt4 key购买 nike

防 rust 代码:

#[repr(C)]
pub struct Tmp {
pub callback: extern "C" fn(i: i32),
}

#[no_mangle]
pub extern "C" fn set_callback(callback: extern "C" fn(i: i32)) -> *mut Tmp {
let mut tmp = Box::new(Tmp { callback });
println!("tmp as ptr: {:p}", tmp); // >> here <<
&mut *tmp
}

#[no_mangle]
pub extern "C" fn use_callback(tmp_ptr: *mut Tmp) {
unsafe {
((*tmp_ptr).callback)(1);
((*tmp_ptr).callback)(3);
}
}

C++代码:

struct Tmp {
void (*callback)(int32_t);
};

typedef Tmp*(__stdcall* set_callback_t)(void(*callback_t)(int32_t));
typedef void(__stdcall* use_callback_t)(Tmp*);

void callback(int32_t i) {
printf("%d\n", i * 2);
}

int main() {
// ... loading rust part as .dll
// ... checking if loaded correctly
Tmp* tmp_ptr = set_callback(callback);
printf("tmp_ptr %p\n", tmp_ptr);
use_callback(tmp_ptr);
// ... freeing the .dll
}

当我编译这个程序时,它按预期工作。 Rust 和 C++ 中指向 Tmp 结构的指针的打印值匹配。当我在 Rust 中注释掉 println 时,C++ 程序崩溃了,这意味着这段(可能是 Rust 部分)代码有问题。

我将 Rust 代码用作 .dll。我想将指向 C++ 函数的指针传递给 set_callback 函数,然后我想在调用 use_callback< 时在 use_callback 函数中使用该指针 在 C++ 代码中。

据我所知,最后我将不得不调用一个 Rust 函数来删除 Tmp 结构,但我没有这样做。

最佳答案

Rust 中的

Box 类似于 C++ 中的 std::unique_ptr。按照您构造 tmp 的方式,指向的数据将在函数结束时被释放。

为了将指针“泄漏”到 C++ 世界中,您应该使用 Box::into_raw .

请注意,不能保证 Rust 和 C++ 以相同的方式分配内存;你必须将指针传递回 Rust 并使用 Box::from_raw释放它。

关于c++ - 分配内存并调用 C++ 回调的 Rust 函数崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50188710/

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