Generate cxx binding in build.rs

This commit is contained in:
topjohnwu
2023-05-19 15:16:54 -07:00
parent 57bd450798
commit 2bcf2e76f1
27 changed files with 169 additions and 49 deletions

View File

@@ -15,6 +15,7 @@ LOCAL_SRC_FILES := \
selinux.cpp \
logging.cpp \
stream.cpp \
base-rs.cpp \
../external/cxx-rs/src/cxx.cc
include $(BUILD_STATIC_LIBRARY)

View File

@@ -6,6 +6,9 @@ edition = "2021"
[lib]
path = "lib.rs"
[build-dependencies]
cxx-gen = { path = "../external/cxx-rs/gen/lib" }
[dependencies]
cxx = { path = "../external/cxx-rs" }
libc = "0.2"

7
native/src/base/build.rs Normal file
View File

@@ -0,0 +1,7 @@
use crate::gen::gen_cxx_binding;
mod gen;
fn main() {
gen_cxx_binding("base-rs");
}

38
native/src/base/gen.rs Normal file
View File

@@ -0,0 +1,38 @@
// This file hosts shared build script logic
use std::fmt::Display;
use std::fs::File;
use std::io::Write;
use std::process;
use cxx_gen::Opt;
trait ResultExt<T> {
fn ok_or_exit(self) -> T;
}
impl<T, E: Display> ResultExt<T> for Result<T, E> {
fn ok_or_exit(self) -> T {
match self {
Ok(r) => r,
Err(e) => {
eprintln!("error occurred: {}", e);
process::exit(1);
}
}
}
}
pub fn gen_cxx_binding(name: &str) {
println!("cargo:rerun-if-changed=lib.rs");
let opt = Opt::default();
let gen = cxx_gen::generate_header_and_cc_with_path("lib.rs", &opt);
{
let mut cpp = File::create(format!("{}.cpp", name)).unwrap();
cpp.write_all(gen.implementation.as_slice()).ok_or_exit();
}
{
let mut hpp = File::create(format!("{}.hpp", name)).unwrap();
hpp.write_all(gen.header.as_slice()).ok_or_exit();
}
}

View File

@@ -5,4 +5,4 @@
#include "../files.hpp"
#include "../misc.hpp"
#include "../logging.hpp"
#include <base-rs.hpp>
#include "../base-rs.hpp"

View File

@@ -6,9 +6,6 @@
#include <flags.h>
#include <base.hpp>
// Just need to include it somewhere
#include <base-rs.cpp>
using namespace std;
static int fmt_and_log_with_rs(LogLevel level, const char *fmt, va_list ap) {

View File

@@ -3,8 +3,6 @@
#include <cerrno>
#include <cstdarg>
#include <base-rs.hpp>
void LOGD(const char *fmt, ...) __printflike(1, 2);
void LOGI(const char *fmt, ...) __printflike(1, 2);
void LOGW(const char *fmt, ...) __printflike(1, 2);

View File

@@ -7,8 +7,6 @@
#include <bitset>
#include <random>
#include <base-rs.hpp>
#define DISALLOW_COPY_AND_MOVE(clazz) \
clazz(const clazz &) = delete; \
clazz(clazz &&) = delete;

View File

@@ -5,7 +5,7 @@
#include <poll.h>
#include <fcntl.h>
#include <base-rs.hpp>
#include "base-rs.hpp"
using rust::xpipe2;