Zngur
Zngur (/zængɑr/) is a C++/Rust interop tool. It tries to expose arbitrary Rust types, methods and functions, while preserving its
semantics and ergonomics as much as possible. Using Zngur, you can use arbitrary Rust crate in your C++ code as easily as using it in
normal Rust code, and you can write idiomatic Rusty API for your C++ library inside C++. See the documentation
for more info.
Demo
#include <iostream>
#include <vector>
#include "./generated.h"
template <typename T> using Vec = rust::std::vec::Vec<T>;
template <typename T> using Option = rust::std::option::Option<T>;
template <typename T> using BoxDyn = rust::Box<rust::Dyn<T>>;
template <typename T>
class VectorIterator : public rust::std::iter::Iterator<T> {
std::vector<T> vec;
size_t pos;
public:
VectorIterator(std::vector<T> &&v) : vec(v), pos(0) {}
~VectorIterator() {
std::cout << "vector iterator has been destructed" << std::endl;
}
Option<T> next() override {
if (pos >= vec.size()) {
return Option<T>::None();
}
T value = vec[pos++];
return Option<T>::Some(value);
}
};
int main() {
auto s = Vec<int32_t>::new_();
s.push(2);
Vec<int32_t>::push(s, 5);
s.push(7);
Vec<int32_t>::push(s, 3);
std::cout << s.clone().into_iter().sum() << std::endl;
try {
std::cout << "s[2] = " << *s.get(2).unwrap() << std::endl;
std::cout << "s[4] = " << *s.get(4).unwrap() << std::endl;
} catch (rust::Panic e) {
std::cout << "Rust panic happened" << std::endl;
}
int state = 0;
auto f = BoxDyn<rust::Fn<int32_t, int32_t>>::make_box([&](int32_t x) {
state += x;
std::cout << "hello " << x << " " << state << "\n";
return x * 2;
});
auto x = s.into_iter().map(std::move(f)).sum();
std::cout << x << " " << state << "\n";
std::vector<int32_t> vec{10, 20, 60};
auto vec_as_iter = BoxDyn<rust::std::iter::Iterator<int32_t>>::make_box<
VectorIterator<int32_t>>(std::move(vec));
auto t = vec_as_iter.collect();
zngur_dbg(t);
}
Output:
17
s[2] = 7
thread '<unnamed>' panicked at 'called `Option::unwrap()` on a `None` value', examples/simple/src/generated.rs:186:39
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
s[4] = Rust panic happened
hello 2 2
hello 5 7
hello 7 14
hello 3 17
34 17
vector iterator has been destructed
[main.cpp:71] t = [
10,
20,
60,
]
See the examples/simple
if you want to build and run it.
License