Skip to content

def_readwrite throws Unicode error when reading from const char * #1168

@RyanJarv

Description

@RyanJarv

def_readwrite throws Unicode error when reading from const char *

Expected

Creating a class from a C struct with const char * and std::string properties should behave the same in both cases.

Reproducible example code

Example repo

https://github.com/RyanJarv/char_struct_bug

Code

#include <pybind11/pybind11.h>

struct string_struct {
    std::string a;
};

struct char_struct {
    const char * a;
};

namespace py = pybind11;

PYBIND11_MODULE(char_struct_bug, m) {
    py::class_<string_struct>(m, "string_struct")
        .def(py::init<>())
        .def_readwrite("a", &string_struct::a);

    py::class_<char_struct>(m, "char_struct")
        .def(py::init<>())
        .def_readwrite("a", &char_struct::a);
}

Output

>>> import char_struct_bug
>>> s = char_struct_bug.string_struct()
>>> s.a = 'asdf'
>>> s.a
'asdf'
>>> c = char_struct_bug.char_struct()
>>> c.a = 'asdf'
>>> c.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 0: invalid continuation byte

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions