Skip to content

[BUG]: function with argument type std::optional<std::reference_wrapper<Eigen::...>> gives segmentation fault #5637

Open
@sin3point14

Description

@sin3point14

Required prerequisites

What version (or hash if on master) of pybind11 are you using?

2.13.6

Problem description

Due to #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

Metadata

Metadata

Assignees

No one assigned

    Labels

    triageNew bug, unverified

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions