[BUG]: function with argument type `std::optional<std::reference_wrapper<Eigen::...>>` gives segmentation fault
Open
Nobody has claimed this yet.
triage
- Dominant language
- C++
- Stars
- 18k
- Forks
- 2.3k
- Avg merge
- 5d 17h
- Merged PRs (30d)
- 10
Description
Required prerequisites
- Make sure you've read the documentation. Your issue may be addressed there.
- Search the issue tracker and Discussions to verify that this hasn't already been reported. +1 or comment there if it has.
- Consider asking first in the Gitter chat room or in a Discussion.
What version (or hash if on master) of pybind11 are you using?
2.13.6
Problem description
Due to https://github.com/pybind/pybind11/issues/5635 I started using std::optional<std::reference_wrapper<...>> and this works fine when I use it as a return value, but crashes when I accept it as an argument to a function.
Reproducible example code
#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>
#include <pybind11/stl.h>
#include <iostream>
#include <Eigen/Eigen>
void print1(std::optional<std::reference_wrapper<Eigen::MatrixXd>> x)
{
std::cout << x.value().get() << std::endl;
}
void print2(std::optional<Eigen::MatrixXd> x)
{
std::cout << x.value() << std::endl;
}
void print3(std::reference_wrapper<Eigen::MatrixXd> x)
{
std::cout << x.get() << std::endl;
}
void print4(Eigen::MatrixXd x)
{
std::cout << x << std::endl;
}
PYBIND11_MODULE(tsting, m)
{
m.def("print1", print1);
m.def("print2", print2);
m.def("print3", print3);
m.def("print4", print4);
}
sin3point14@DESKTOP-D97C2FN:~/random/cpp/pybind11-test$ python3
Python 3.12.3 (main, Feb 4 2025, 14:48:35) [GCC 13.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tsting
>>> import numpy as np
>>> a = np.ones((2,2))
>>> a
array([[1., 1.],
[1., 1.]])
>>> tsting.print4(a)
1 1
1 1
>>> tsting.print3(a)
1 1
1 1
>>> tsting.print2(a)
1 1
1 1
>>> tsting.print1(a)
Segmentation fault (core dumped)
Is this a regression? Put the last known working version here if it is.
Not a regression
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the crash with the provided bindings and NumPy example, then read pybind11/eigen.h, pybind11/stl.h, and pybind11/pybind11.h around argument conversion for std::optional and std::reference_wrapper. Done means print1(a) no longer segfaults while the existing print2, print3, and print4 behavior remains intact.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp, python
- Domain
- backend-api-design
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100