cxx icon indicating copy to clipboard operation
cxx copied to clipboard

Support for const?

Open lukaz-vaultree-com opened this issue 3 years ago • 1 comments

fn some_type(some_arg: u32) -> UniquePtr<CxxVector<SomeType>>;

but on the C++ side I needed to return std::unique_ptr<const std::vector<SomeType>>

lukaz-vaultree-com avatar Jan 27 '22 11:01 lukaz-vaultree-com

The CxxVector binding on the Rust side specifically refers to std::vector<T>. If you have signatures needing to use const std::vector<T>, that's just some other extern C++ type, which should already work with cxx. Something like:

// src/main.rs

#[cxx::bridge]
mod ffi {
    unsafe extern "C++" {
        include!("example/include/header.h");

        type SomeType;
        fn some_type(some_arg: u32) -> UniquePtr<ConstVectorSomeType>;
        fn example(self: &SomeType) -> &CxxString;

        type ConstVectorSomeType;
        fn size(self: &ConstVectorSomeType) -> usize;
        fn at(self: &ConstVectorSomeType, i: usize) -> &SomeType;
    }
}

fn main() {
    let vector = ffi::some_type(0);
    println!("{}", vector.size());
    println!("{}", vector.at(0).example());
}
// include/header.h

#pragma once
#include <memory>
#include <string>
#include <vector>

struct SomeType {
  std::string demo;
  const std::string& example() const;
};

using ConstVectorSomeType = const std::vector<SomeType>;

std::unique_ptr<const std::vector<SomeType>> some_type(uint32_t some_arg);
// src/demo.cc

#include "example/include/header.h"

std::unique_ptr<const std::vector<SomeType>> some_type(uint32_t some_arg) {
  (void)some_arg;
  std::vector<SomeType> v = {SomeType{"a"}, SomeType{"b"}};
  return std::make_unique<const std::vector<SomeType>>(std::move(v));
}

const std::string& SomeType::example() const { return demo; }

dtolnay avatar Jan 27 '22 19:01 dtolnay