cxx icon indicating copy to clipboard operation
cxx copied to clipboard

Exposing shared constants

Open str4d opened this issue 2 years ago • 2 comments

I'd like to be able to expose Rust constants (for the purpose of this issue, assume only const primitives) to C++, so they are defined in a single location. For example, I'd like to write something like:

#[cxx::bridge(namespace = "blake2b")]
mod ffi {
    const PERSONALBYTES: usize = blake2b_simd::PERSONALBYTES;
}

or

#[cxx::bridge(namespace = "blake2b")]
mod ffi {
    const PERSONALBYTES;
}

const PERSONALBYTES: usize = blake2b_simd::PERSONALBYTES;

and have this be accessible from C++ as blake2b::PERSONALBYTES with type size_t.

str4d avatar May 26 '22 14:05 str4d

This is something I'd like to achieve as well. I looked at your PR there on zcash/zcash#5971, @str4d - did you manage to find a workaround?

shymega avatar Mar 26 '23 22:03 shymega

Probably this:

// .rs

#[cxx::bridge(namespace = "blake2b")]
mod ffi {
    extern "Rust" {
        fn get_personalbytes() -> usize;
    }
}

fn get_personalbytes() -> usize { blake2b_simd::PERSONALBYTES }
// .h

#pragma once
#include <cstddef>

namespace blake2b {
std::size_t const extern PERSONALBYTES;
}
// .cpp

#include "path/to/this.h"
#include "path/to/this.rs.h"

std::size_t const blake2b::PERSONALBYTES = get_personalbytes();

or this:

// .rs

#[no_mangle]
#[export_name = "blake2b_simd$PERSONALBYTES"]
pub static blake2b_simd_PERSONALBYTES: usize = blake2b_simd::PERSONALBYTES;
// .h

#pragma once
#include <cstddef>

std::size_t const extern blake2b_simd$PERSONALBYTES;

namespace blake2b {
std::size_t const static PERSONALBYTES = blake2b_simd$PERSONALBYTES;
}

dtolnay avatar Mar 26 '23 23:03 dtolnay