T must not be an opaque Rust type or opaque C++ type. Support for opaque Rust
types in slices is coming.
Allowed as function argument or return value. Not supported in shared structs.
Only rust::Slice<const T> is copy-assignable, not rust::Slice<T>. (Both are
move-assignable.) You'll need to write std::move occasionally as a reminder that
accidentally exposing overlapping &mut [T] to Rust is UB.
This example is a C++ program that constructs a slice containing JSON data (by
reading from stdin, but it could be from anywhere), then calls into Rust to
pretty-print that JSON data into a std::string via the serde_json and
serde_transcode crates.
// src/main.rs#![no_main]// main defined in C++ by main.ccuse cxx::CxxString;
use std::io::{self, Write};
use std::pin::Pin;
#[cxx::bridge]mod ffi {
extern"Rust" {
fnprettify_json(input: &[u8], output: Pin<&mut CxxString>) -> Result<()>;
}
}
structWriteToCxxString<'a>(Pin<&'amut CxxString>);
impl<'a> Write for WriteToCxxString<'a> {
fnwrite(&mutself, buf: &[u8]) -> io::Result<usize> {
self.0.as_mut().push_bytes(buf);
Ok(buf.len())
}
fnflush(&mutself) -> io::Result<()> {
Ok(())
}
}
fnprettify_json(input: &[u8], output: Pin<&mut CxxString>) -> serde_json::Result<()> {
let writer = WriteToCxxString(output);
letmut deserializer = serde_json::Deserializer::from_slice(input);
letmut serializer = serde_json::Serializer::pretty(writer);
serde_transcode::transcode(&mut deserializer, &mut serializer)
}
// src/main.cc#include"example/src/main.rs.h"#include<iostream>#include<iterator>#include<string>#include<vector>intmain(){
// Read json from stdin.std::istreambuf_iterator<char> begin{std::cin}, end;
std::vector<unsignedchar> input{begin, end};
rust::Slice<constuint8_t> slice{input.data(), input.size()};
// Prettify using serde_json and serde_transcode.std::string output;
prettify_json(slice, output);
// Write to stdout.std::cout << output << std::endl;
}
Testing the example:
$echo'{"fearless":"concurrency"}' | cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.02s
Running `target/debug/example`
{
"fearless": "concurrency"
}