libqe 0.2.5
QE C++ library
Loading...
Searching...
No Matches
cxxwrap.hpp
Go to the documentation of this file.
1
12#ifndef LIBQE_BIND_CXXWRAP_HPP
13#define LIBQE_BIND_CXXWRAP_HPP
14
15#include <jlcxx/jlcxx.hpp>
16#include <jlcxx/array.hpp>
17
18#include <armadillo>
19#include <cstdint>
20#include <stdexcept>
21#include <vector>
22
23namespace qe {
24namespace bind {
25namespace jl {
26
27// Julia array (column-major) → zero-copy arma::mat view.
28// CAUTION: the arma::mat must not outlive the Julia array.
29inline arma::mat view_mat(jlcxx::ArrayRef<double> data, int rows, int cols) {
30 return arma::mat(data.data(), static_cast<arma::uword>(rows),
31 static_cast<arma::uword>(cols),
32 /*copy_aux_mem=*/false, /*strict=*/true);
33}
34
35// arma::mat → std::vector<double> (column-major; Julia reshape is zero-copy).
36inline std::vector<double> pack(const arma::mat& m) {
37 return std::vector<double>(m.memptr(), m.memptr() + m.n_elem);
38}
39
40// arma::rowvec → std::vector<double>
41inline std::vector<double> pack(const arma::rowvec& v) {
42 return std::vector<double>(v.memptr(), v.memptr() + v.n_elem);
43}
44
45// Julia Matrix{Int32} (column-major) → arma::imat.
46// Cannot be zero-copy: arma::sword is s32 or s64 depending on ARMA_64BIT_WORD,
47// so we always copy with an explicit cast.
48inline arma::imat copy_imat(jlcxx::ArrayRef<int32_t> data, int rows, int cols) {
49 arma::imat m(static_cast<arma::uword>(rows),
50 static_cast<arma::uword>(cols));
51 // data is column-major (Julia-native), matching Armadillo's layout
52 for (arma::uword j = 0; j < static_cast<arma::uword>(cols); ++j)
53 for (arma::uword i = 0; i < static_cast<arma::uword>(rows); ++i)
54 m(i, j) = static_cast<arma::sword>(data[j * rows + i]);
55 return m;
56}
57
58// Unpack a jl_value_t* (expected to be Vector{Float64}) into arma::vec.
59// Used to interpret the return value of a Julia callback (e.g. a decay
60// function).
61inline arma::vec unpack_jl_vec(jl_value_t* val) {
62 if (!jl_is_array(val))
63 throw std::runtime_error("decay_fn must return a Vector{Float64}");
64 auto* arr = reinterpret_cast<jl_array_t*>(val);
65 return arma::vec(jl_array_data(arr, double),
66 static_cast<arma::uword>(jl_array_len(arr)),
67 /*copy=*/false);
68}
69
70} // namespace jl
71} // namespace bind
72} // namespace qe
73
74#endif // LIBQE_BIND_CXXWRAP_HPP
arma::vec unpack_jl_vec(jl_value_t *val)
Definition cxxwrap.hpp:61
arma::mat view_mat(jlcxx::ArrayRef< double > data, int rows, int cols)
Definition cxxwrap.hpp:29
std::vector< double > pack(const arma::mat &m)
Definition cxxwrap.hpp:36
arma::imat copy_imat(jlcxx::ArrayRef< int32_t > data, int rows, int cols)
Definition cxxwrap.hpp:48
Definition adjacency.hpp:16