c++ - 如何取消引用 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 中以结构或函数的形式转换数据?
解决方案
你可以在 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 };
}
推荐阅读
- c# - EF Core 设置环境无法按预期工作
- c# - 从动态构建的数据集创建报告
- sql - Oracle listagg - 我可以根据 listagg 选择的值从其他表中提取数据吗
- git - 支持除 GitHub 之外的其他 git 存储库
- tensorflow - 让 Tensorboard Profiler 在 Windows 中运行
- excel - 将范围设置为最后一行和打印区域结束之间的空白空间 - Excel VBA PrintArea
- java - 在 Java 中使用泛型接口作为方法参数
- c# - 使用 Apache Docker 在 Linux 中托管 ASP.NET Core
- c - 释放链表内存时的 valgrind 错误
- python - 来自子解析器的顶级解析器上的 Python argparse set_defaults