[CXX] Rust -> C++

I am trying to compile with rust library in c++ code (main.cpp) with cxx.rs
I have a problem with it. File lib.rs.h not generate.

// src/lib.rs

use cxx::CxxString;
use std::io::{self, Write};
use std::pin::Pin;

mod ffi {
 extern "Rust" {
   fn prettify_json(
            input: &[u8], 
            output: Pin<&mut CxxString>) -> Result<()>;

struct WriteToCxxString<'a>(Pin<&'a mut CxxString>);

impl<'a> Write for WriteToCxxString<'a> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
    fn flush(&mut self) -> io::Result<()> {

fn prettify_json(input: &[u8], 
                 output: Pin<&mut CxxString>) -> serde_json::Result<()> 
    let writer = WriteToCxxString(output);
    let mut deserializer = serde_json::Deserializer::from_slice(input);
    let mut serializer = serde_json::Serializer::pretty(writer);
    serde_transcode::transcode(&mut deserializer, &mut serializer)
// src/main.cpp

#include "lib.rs.h"

#include <iostream>
#include <iterator>
#include <string>
#include <vector>

int main() 
  // Read json from stdin.
  std::istreambuf_iterator<char> begin{std::cin}, end;
  std::vector<unsigned char> input{begin, end};
  rust::Slice<const uint8_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;


name = "cxx-rust"
edition = "2018"
version = "0.1.0"
authors = ["Michał Hanusek <mhanusek@o2.pl>"]

cxx = "*"
serde = { version = "1", features = ["derive"] }
serde_json = "*"
serde-transcode = "*"

crate-type = ["staticlib"]

Repo with code:

Can you be more specific here?

For example, are you running into a compiler error while generating lib.rs.h, or is CMake unable to locate lib.rs.h? if so, are you using cxxbridge to generate the bridge's *.h and *.c file?

1 Like

Thx. I have the next problem - linking.

cmake_minimum_required(VERSION 3.9 FATAL_ERROR)


add_executable(app ${CMAKE_SOURCE_DIR}/src/main.cpp)
target_link_libraries(app ${CMAKE_SOURCE_DIR}/target/debug/libcxx_rust.a -Wl,--allow-multiple-definition -ldl -lpthread)

Error log:

[100%] Linking CXX executable app
CMakeFiles/app.dir/src/main.cpp.o: In function `main':
main.cpp:(.text+0xd9): undefined reference to `prettify_json(rust::cxxbridge1::Slice<unsigned char const>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&)'
collect2: error: ld returned 1 exit status

I solved it based on: GitHub - XiangpengHao/cxx-cmake-example: An example repo to setup cxx (Rust FFI library) with the CMake build system.
My solution:
GitHub - hanusek/rust-cxx: rust & cpp interop

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.