pybind11 icon indicating copy to clipboard operation
pybind11 copied to clipboard

Problems of exposing const char * field in struct

Open zhanghb97 opened this issue 6 years ago • 11 comments

Hi,

I found binding a struct contains const char * field may cause problems in my project. When I get a struct object from a function, the const char * field will be empty. Here I use a prototype to show three situations:

// struct contains const char * field and other field.
struct A {
  const char *a1;
  int a2;
};
typedef struct A A;
A initA(const char *a1, int a2) {
  return A{a1, a2};
}

// struct contains const char * field and a nested struct.
struct B {
  const char * b;
  A a;
};
typedef struct B B;
B initB(const char *b, A a) {
  return B{b, a};
}

// struct only contains const char * field.
struct C {
  const char *c;
};
typedef struct C C;

C initC(const char *c) {
  return C{c};
}

And I use the following code to expose the fields in the struct:

PYBIND11_MODULE(test, m) {
  py::class_<A>(m, "A")
    .def_readwrite("a1", &A::a1)
    .def_readwrite("a2", &A::a2);
  m.def("initA", &initA);
  
  py::class_<B>(m, "B")
    .def_readwrite("b", &B::b)
    .def_readwrite("a", &B::a);
  m.def("initB", &initB);

  py::class_<C>(m, "C")
    .def_readwrite("c", &C::c);
  m.def("initC", &initC);
}

The results:

>>> import test
>>> test_a = test.initA("test_a", 10)
>>> test_b = test.initB("test_b", test_a)
>>> test_c = test.initC("test_c")
>>> print(test_a.a1)

>>> print(test_b.b)

>>> print(test_c.c)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf0 in position 0: invalid continuation byte

The expected output should be:

>>> print(test_a.a1)
test_a
>>> print(test_b.b)
test_b
>>> print(test_c.c)
test_c

But the actual output is empty and UnicodeDecodeError. I tried def_readonly and def_readwrite to expose the const char * field, but they cause the same problem. I'm not sure is this because the lifetime of const char * has already ended when I want to print it? And why the string caused the UnicodeDecodeError? Am I missing something important, how could I solve these problems without touching the source code?

Thanks!

zhanghb97 avatar Jul 28 '20 12:07 zhanghb97

Pybind11 intentionally doesn't deal with pointers-as-arrays. Wrap that thing in a lambda and return a py::str().

bstaletic avatar Jul 28 '20 12:07 bstaletic

Pybind11 intentionally doesn't deal with pointers-as-arrays.

Actually, it does for strings as char *s?

I'm not sure is this because the lifetime of const char * has already ended when I want to print it?

But yes, you're right. You cannot just accept a const char * in a function and just expect it will have the right ownership/lifetime for your use case. The const char * that pybind11 offers points to a temporary string, so you can't just store it in the struct. Wrap it in a lambda that copies it, or take a std::string and copy it, or ... whatever matches your expected lifetime/ownership semantics. Or even better: use std::string and you don't have to think about who owns what.

Returning should be fine; pybind11 makes a copy anyway.

YannickJadoul avatar Jul 28 '20 13:07 YannickJadoul

(PS: For these kinds of questions that aren't particularly suspected bugs/issues, there's also Gitter where you might get an answer sooner.)

YannickJadoul avatar Jul 28 '20 13:07 YannickJadoul

Maybe closing this issue was too soon. Does that approach actually work for you, @zhanghb97?

YannickJadoul avatar Jul 28 '20 15:07 YannickJadoul

@YannickJadoul , I tried to copy the const char * by memcpy and std::string, and I found I should allocate a huge space (char n[2000];) so that the string ("test_c") can print correctly. For example:

C initC(const char *c) {
  char n[2000];
  memcpy(n, c, strlen(c)+1);
  return C{n};
}

Result:

>>> test_c = test.initC("test_c")
>>> print(test_c.c)
test_c

If I don't allocate that huge space, it will report the UnicodeDecodeError: invalid continuation byte, it seems that the string is not completely saved.

As for the std::string:

C initC(const char *c) {
  std::string n = c;
  return C{n.data()};
}

I cannot modify the struct in my project, so I should convert std::string to const char *, and then initial the struct object. It also cause the same problem: UnicodeDecodeError: invalid continuation byte.

Why does the string need such a huge space? Is my copying process correct?

zhanghb97 avatar Jul 28 '20 16:07 zhanghb97

Don't do that. Instead of:

    .def_readwrite("a1", &A::a1)

do this:

    .def_property("a1", [])
.def_property("a1", [](const A& self) -> py::str { return self.a1; },
		   [](A& self, conststd::string& new_a1) { self.a1 = realloc(new_a1.size() + 1); strcpy(self.a1, new_a1.data()); });

And similarly for B::b and C::c.

Your initC could be bound like this:

py::class_<C>(m, "C")
    .def("__init__" [](const std::string& new_c) {
        char* c = malloc(new_c.size() + 1);
        strcpy(c, new_a1.data());
        return initC(c);
    });

This will work, but this is in no way good C++. Funnily enough, this isn't even good C. No matter how you look at it, what I've just written is bad and does a ton more copying than needed, but that's partially CPython's fault, partially the fault of mixing C and C++ so intrusively.

bstaletic avatar Jul 28 '20 17:07 bstaletic

@YannickJadoul , I tried to copy the const char * by memcpy and std::string, and I found I should allocate a huge space (char n[2000];) so that the string ("test_c") can print correctly. For example:

C initC(const char *c) {
  char n[2000];
  memcpy(n, c, strlen(c)+1);
  return C{n};
}

@zhanghb97 This is still copying stuff into a local buffer that's disappearing at the end of the constructing function. So the pointer you store in the class points to memory in the stack that's gone. Probably by making it so big, you make sure it doesn't get overwritten again; yet it's still undefined behavior!

Doing it with a string won't help, if you don't save the string

@bstaletic's approach is closer to what you need, though you'll be leaking memory, if you don't provide a destructor (or a destroyC function that you'd call) !

YannickJadoul avatar Jul 28 '20 21:07 YannickJadoul

I'll close this now, as we've established that pybind11 is not to blame. Feel free to continue the conversation (or even easier: come to Gitter).

YannickJadoul avatar Jul 28 '20 21:07 YannickJadoul

@YannickJadoul @bstaletic Thanks for your help! Now I use a lambda expression to copy the string and wrap the initC:

m.def("initC", [](const char *new_c) -> C {
  char* c = (char *)malloc(sizeof(new_c));
  strcpy(c, new_c);
  return initC(c);
});

It works correctly:

>>> test_c = test.initC("test_c")
>>> print(test_c.c)
test_c

If I have further questions, I will ask in the Gitter.

zhanghb97 avatar Jul 29 '20 09:07 zhanghb97

Great, thanks! Issues can still be created, ofc, but it's easier to quickly judge these kinds of things on Gitter. Most of the time, someone is there, who knows what he/she is talking about!

YannickJadoul avatar Jul 29 '20 14:07 YannickJadoul

@YannickJadoul @bstaletic Thanks for your help! Now I use a lambda expression to copy the string and wrap the initC:

m.def("initC", [](const char *new_c) -> C {
  char* c = (char *)malloc(sizeof(new_c));
  strcpy(c, new_c);
  return initC(c);
});

It works correctly:

>>> test_c = test.initC("test_c")
>>> print(test_c.c)
test_c

If I have further questions, I will ask in the Gitter.

hi, i have another question. Every time the program calls initC will leads to a new memory allocation. Is it good for memory management or will it cause memory leak? Thanks. @zhanghb97

ehuaa avatar Jun 28 '23 07:06 ehuaa