diff --git a/Cargo.lock b/Cargo.lock index 05aba87..8af90fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -251,6 +251,7 @@ name = "tictactoe-rust-foropenspiel" version = "0.1.0" dependencies = [ "cxx", + "cxx-build", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 0a071d9..2323eb6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,3 +5,6 @@ edition = "2024" [dependencies] cxx = "1.0.192" + +[build-dependencies] +cxx-build = "1.0.192" diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..5b40c01 --- /dev/null +++ b/build.rs @@ -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"); +} diff --git a/include/main.h b/include/main.h new file mode 100644 index 0000000..c8da83d --- /dev/null +++ b/include/main.h @@ -0,0 +1,3 @@ +#pragma once + +void run_cpp_demo(); diff --git a/src/game.rs b/src/game.rs index c318016..ad50d72 100644 --- a/src/game.rs +++ b/src/game.rs @@ -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(); } } diff --git a/src/main.cc b/src/main.cc new file mode 100644 index 0000000..45d42ec --- /dev/null +++ b/src/main.cc @@ -0,0 +1,21 @@ +#include "tictactoe-rust-foropenspiel/include/main.h" +#include "tictactoe-rust-foropenspiel/src/game.rs.h" +#include +#include +#include +#include + +void run_cpp_demo() { + rust::Box game = init(); + + std::random_device rd; + std::mt19937 gen(rd()); + + rust::Vec actions = game->legal_actions(); + while (!actions.empty()) { + std::uniform_int_distribution dis(0, actions.size() - 1); + game->do_action(actions[dis(gen)]); + actions = game->legal_actions(); + } + std::cout << "Result: \n" << game->to_string().c_str(); +} diff --git a/src/main.rs b/src/main.rs index 06394c2..8baa5f8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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 ---"); +} \ No newline at end of file