首页 > 解决方案 > 如何取消引用 C/C++ void * 到 Rust 中的结构或回调?

问题描述

我想用 Rust 为一个老游戏写一个 AI。该游戏的 AI 是库,在其 Linux 端口中它只是一个.so文件导出:

extern "C" void client(int Command, int Player, void *Data);

void *Data可以是结构(取决于Command)或此函数:

typedef int TServerCall(int Command, int Player, int Subject, void *Data);

在 C++ 中,AI 代码根据命令将其转换为已知大小或回调的结构,例如:

typedef int __stdcall TServerCall(int Command, int Player, int Subject, void *Data);

或构造:

// where G is a extern TNewGameData G;

G = *(TNewGameData *) Data;

然后我可以访问G其他结构或数组的字段。

问题:

如何void *在 Rust 中以结构或函数的形式转换数据?

标签: c++rustffi

解决方案


你可以在 Rust 中转换原始指针。

use libc::{c_void, c_int};

#[repr(C)]
struct TNewGameData {
    // the fields go here
}

#[no_mangle]
pub extern "C" fn client(command: c_int, player: c_int, data: *mut c_void) {
    // Cast raw pointer to the right type.
    let game_data_ptr = data as *mut TNewGameData;
    // Convert to Rust reference.
    let game_data = unsafe { &mut *data };
}

推荐阅读