Pass std::string from Python binder

Here's the place for discussion related to coding in FreeCAD, C++ or Python. Design, interfaces and structures.
openBrain
Posts: 5927
Joined: Fri Nov 09, 2018 5:38 pm

Pass std::string from Python binder

Postby openBrain » Sun May 09, 2021 6:14 pm

Hi all,

I'm encountering an issue (more precisely a segmentation fault) while trying to pass a "Python" string to a std::string as function argument while trying to build a binder.
Some more details.
The C++ signature of the function to be called is :

Code: Select all

bool FooClass::FooFunc(std::string);
And how basically looks the (faulty) binder:

Code: Select all

PyObject* FooClass::sFooFunc(PyObject * /*self*/, PyObject *args)
{
    PyObject* obj;
    if (!PyArg_ParseTuple(args, "s", &obj))
        return NULL;
    bool ok = FooFunc(Py::Object(obj).as_string());
    return Py::new_reference_to(Py::Boolean(ok));
}
The segmentation fault comes from this line :

Code: Select all

bool ok = FooFunc(Py::Object(obj).as_string());
in the 'as_string()' function.

I also tried

Code: Select all

bool ok = FooFunc(Py::String(obj).as_string());
but it also segfaults in 'String()' constructor.

May one know what is the proper way to convert the binder string argument into an std::string and pass it to the function ?
TIA