Skip to content
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

[BUG]: Incorrect values for first-several elements of Eigen::Vector when exposed with def_prop_ro #971

Open
zhipzhang opened this issue Mar 14, 2025 · 0 comments

Comments

@zhipzhang
Copy link

Problem description

Description

I'm encountering an issue where the first few elements of an Eigen::VectorXf are incorrect when accessed from Python after being exposed as a read-only property using def_prop_ro. Specifically, the first four elements appear to have erroneous values. Using def to expose the same data as a method, or using std::vector instead of Eigen::VectorXf, works correctly. This suggests a potential incompatibility or bug related to how def_prop_ro handles Eigen::VectorXf.

The results are shown in the figure:

Image

Reproducible example code

#include <nanobind/nanobind.h>
#include <nanobind/eigen/dense.h>
#include <Eigen/Dense>
#include <vector>

namespace nb = nanobind;

class test_Histogram2D {
public:
    test_Histogram2D(float min, float max, int bins) {
        bins_ = bins;
        min_ = min;
        max_ = max;
    }

    Eigen::VectorXf centers_eigen() const {
        Eigen::VectorXf centers(bins_);
        for (int i = 0; i < bins_; i++) {
            centers(i) = get_bin_center(i);
        }
        return centers;
    }

    std::vector<float> centers_stdvector() const {
        std::vector<float> centers(bins_);
        for (int i = 0; i < bins_; i++) {
            centers[i] = get_bin_center(i);
        }
        return centers;
    }

    float get_bin_center(int idx) const {
        return min_ + (idx + 0.5f) * (max_ - min_) / (float)bins_;
    }

private:
    int bins_;
    float min_;
    float max_;
};

NB_MODULE(example, m) {
    nb::class_<test_Histogram2D>(m, "test_Histogram2D")
        .def(nb::init<float, float, int>())
        .def_prop_ro("centers_eigen", &test_Histogram2D::centers_eigen)
        .def("centers_method", &test_Histogram2D::centers_eigen) // Working method version
        .def("centers_stdvector", &test_Histogram2D::centers_stdvector); //Also working
}
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

1 participant