cxx: expose c++ code

This commit is contained in:
Henri Bourcereau 2026-01-02 20:58:10 +01:00
parent efa1543eaf
commit a17f8e2f73
7 changed files with 44 additions and 11 deletions

1
Cargo.lock generated
View file

@ -251,6 +251,7 @@ name = "tictactoe-rust-foropenspiel"
version = "0.1.0"
dependencies = [
"cxx",
"cxx-build",
]
[[package]]

View file

@ -5,3 +5,6 @@ edition = "2024"
[dependencies]
cxx = "1.0.192"
[build-dependencies]
cxx-build = "1.0.192"

9
build.rs Normal file
View file

@ -0,0 +1,9 @@
fn main() {
cxx_build::bridge("src/game.rs")
.file("src/main.cc")
.compile("tictactoe-rust-foropenspiel");
println!("cargo:rerun-if-changed=src/game.rs");
println!("cargo:rerun-if-changed=src/game.cc");
println!("cargo:rerun-if-changed=include/game.h");
}

3
include/main.h Normal file
View file

@ -0,0 +1,3 @@
#pragma once
void run_cpp_demo();

View file

@ -1,7 +1,7 @@
use std::{fmt, str};
#[cxx::bridge]
mod ffi {
pub mod ffi {
// Rust types and signatures exposed to C++.
extern "Rust" {
type Player;
@ -15,6 +15,8 @@ mod ffi {
// C++ types and signatures exposed to Rust.
unsafe extern "C++" {
include!("tictactoe-rust-foropenspiel/include/main.h");
fn run_cpp_demo();
}
}

21
src/main.cc Normal file
View file

@ -0,0 +1,21 @@
#include "tictactoe-rust-foropenspiel/include/main.h"
#include "tictactoe-rust-foropenspiel/src/game.rs.h"
#include <iomanip>
#include <iostream>
#include <random>
#include <vector>
void run_cpp_demo() {
rust::Box<GameState> game = init();
std::random_device rd;
std::mt19937 gen(rd());
rust::Vec<size_t> actions = game->legal_actions();
while (!actions.empty()) {
std::uniform_int_distribution<size_t> dis(0, actions.size() - 1);
game->do_action(actions[dis(gen)]);
actions = game->legal_actions();
}
std::cout << "Result: \n" << game->to_string().c_str();
}

View file

@ -1,13 +1,7 @@
mod game;
use game::GameState;
fn main() {
let mut game = GameState::default();
let mut actions = game.legal_actions();
while !actions.is_empty() {
game.do_action(actions[0]);
actions = game.legal_actions();
}
println!("Result: \n{game}");
}
println!("--- Calling C++ from Rust ---");
game::ffi::run_cpp_demo();
println!("--- Back in Rust ---");
}