Skip to content

Support for const? #1006

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
lukaz-vaultree-com opened this issue Jan 27, 2022 · 1 comment
Open

Support for const? #1006

lukaz-vaultree-com opened this issue Jan 27, 2022 · 1 comment

Comments

@lukaz-vaultree-com
Copy link

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>>

@dtolnay
Copy link
Owner

dtolnay commented Jan 27, 2022

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; }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants