pybind / pybind/pybind11

[QUESTION] Binding an Eigen::ArrayxxD derived class

Open
#3,028 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

Hi,

I'm new to Pybind11, and I am trying to bind a custom C++ class derived from Eigen::Arrayxxd.
I understand that pybind provides automatic conversion of Eigen types to numpy arrays, but ideally, I'd like to keep the structure of my class while getting access to the stored data, be it a numpy array or something more custom made.

Here is a simplified version of the code :

class Grid : public Eigen::ArrayXXd
	{
	public:
		double Lx = 0., Ly = 0.;

		using Eigen::ArrayXXd::ArrayXXd;

		CORE_API static Grid set_Size(size_t x, size_t y, double lx, double ly, double val = 0.);
	};

and the binding :

void bind_grid(py::module& m)
{
py::class_<Grid> pyGrid(m, "Grid", "Grid");
	pyGrid.def(py::init<>(), "constructor")
		.def_static("set_Size", &Grid::set_Size)

}

If I use #include <pybind11/eigen.h> , I can create a Grid object in python, but as soon as I use a method that returns a Grid (for example set_Size()), it gets translated to a numpy array automatically.
If I remove the include, the object returned is a Grid, but I can't access the stored data anymore.

I could implement operators and accessors for the stored data when using solution 2, but I assume there is a more straight forward solution ?

Any help would be much appreciated !

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the shown Grid binding and compare its behavior with and without pybind11/eigen.h. Determine whether the requested preservation of Grid objects and access to their stored data is supported, and document or demonstrate the resulting binding approach.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.