python - Pass std::string into PyObject_CallFunction -
when run presult = pyobject_callfunction(pfunc, "s", &"string")
, python script returns correct string. but, if try run this:
std::string passedstring = "string"; presult = pyobject_callfunction(pfunc, "s", &passedstring)
then convert presult std::string
, <null>
when print it. here (probably) complete code returns <null>
:
c++ code:
#include <python.h> #include <string> #include <iostream> int main() { pyobject *pname, *pmodule, *pdict, *pfunc; // set pythonpath working directory setenv("pythonpath",".",1); //this doesn't setenv("pythondontwritebytecode", " ", 1); // initialize python interpreter py_initialize(); // build name object pname = pyunicode_fromstring((char*)"string"); // load module object pmodule = pyimport_import(pname); // pdict borrowed reference pdict = pymodule_getdict(pmodule); // pfunc borrowed reference pfunc = pydict_getitemstring(pdict, (char*)"getstring"); if (pfunc != null) { if (pycallable_check(pfunc)) { pyobject *presult; std::string passedstring = "string"; presult = pyobject_callfunction(pfunc, "s", &passedstring); pyobject* presultstr = pyobject_repr(presult); std::string returnedstring = pyunicode_asutf8(presultstr); std::cout << returnedstring << std::endl; py_decref(presult); py_decref(presultstr); } else {pyerr_print();} } else {std::cout << "pfunc null!" << std::endl;} // clean py_decref(pfunc); py_decref(pdict); py_decref(pmodule); py_decref(pname); // finish python interpreter py_finalize(); }
python script (string.py):
def getstring(returnstring): return returnstring
i'm on ubuntu (linux) , i'm using python 3.4
you should pass c-style string pyobject_callfunction
code work. in order c-string std::string
, use c_str()
method. following line:
presult = pyobject_callfunction(pfunc, "s", &passedstring);
should this:
presult = pyobject_callfunction(pfunc, "s", passedstring.c_str());
Comments
Post a Comment