osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Help on convert PyObject to string (c) Python 3.6


Hi Chris,

   Thanks a lot ! Using PyUnicode_DecodeUTF8 fix the problem.



On Sun, Feb 4, 2018 at 12:02 PM, Chris Angelico <rosuav at gmail.com> wrote:

> On Mon, Feb 5, 2018 at 3:52 AM, Jason Qian via Python-list
> <python-list at python.org> wrote:
> > Hi,
> >
> >    This is the case of calling python from c and the python function
> will
> > return a string.
> >
> >    It seems python been called correctly, but got error when convert the
> > python string to c string.
> >
> > -- c --
> >
> >    PyObject* pValue = PyObject_CallObject(pFunc, pArgs);
> >
> >
> > -- python --
> >
> > import string, random
> > def StringGen(argv):
> >     out_string_size=int(argv);
> >     output_data=''.join(random.choice(string.ascii_lowercase) for x in
> > range(out_string_size))
> >     return output_data
> >
> >
> > I try:
> >
> >  PyObject* pValue = PyObject_CallObject(pFunc, pArgs);
> > const char* sp = 0;
> > if (!PyArg_ParseTuple(pValue, "s", &sp)) {
> > }
> >
> > and got
> >
> > "SystemError: new style getargs format but argument is not a tuple"
> >
>
> You're using something that is specifically for parsing *arguments*
> (as indicated by the "PyArg" prefix). If you want to get a 'const char
> *' from a Python string, you probably want to encode it UTF-8. There's
> a convenience function for that:
>
> https://docs.python.org/3/c-api/unicode.html#c.PyUnicode_AsUTF8AndSize
>
> And if you know for sure that there won't be any \0 in the string, you
> can use the next function in the docs, which doesn't bother returning
> the size. (It'll always be null-terminated.)
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>