Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ embedded python PyArg_ParseTuple fails with string args
    primarykey
    data
    text
    <p>I'm trying to add embedded python to a OpenGL/SDL application. So far everything works fine, like entering a string via SDL keyboard events and executing it with the embedded python interpreter. I'm now into adding functions to call C/C++ functions like</p> <pre><code>void set_iterations(int c); </code></pre> <p>is invoked on the python interpreter with</p> <pre><code>&gt;&gt;&gt; test.iterations(23) </code></pre> <p>The parsing of the integer parameter works like charm</p> <pre><code>static PyObject* test_iterations(PyObject *self, PyObject *args) { int iterations; PyArg_ParseTuple(args,"i",&amp;iterations); set_iterations(iterations); return Py_None; } </code></pre> <p>But when I try this: <code>&gt;&gt;&gt; test.addignore('something')</code></p> <pre><code>static PyObject* test_addignore(PyObject *self, PyObject *args) { char* ignorestring; //PyArg_ParseTuple(args,"s",ignorestring); PyArg_ParseTuple(args,"s",&amp;ignorestring); add_global_ignore(ignorestring); // C function return Py_None; } </code></pre> <p>Python gives me this error:</p> <pre><code>Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-3: invalid data </code></pre> <p>The string should be UTF-8, as SDL is set to grab UNICODE from the keyboard, and everything else works perfectly.</p> <p>Does anyone have an idea on what I might be doing wrong here?</p> <p>I also inspected the args object passed to the function with</p> <pre><code>std::string args_str; PyObject* repr = PyObject_Repr(args); if (repr != NULL) { args_str = PyBytes_AsString(PyUnicode_AsEncodedString(repr, "utf-8", "Error")); Py_DECREF(repr); } std::cout &lt;&lt; args_str &lt;&lt; "\n"; </code></pre> <p>And it gives me this: <code>('somestring',)</code></p> <hr> <p>Solution: The error pointed out by rodrigo, was originally causing be believe that my debug code that should print the resulting string as PyObject was wrong. But the problem was that I was passing the parser the wrong pointer, leading to said undefined behaviour in the memory and therefore leading me to believe the parser was the problem. The occurring last parser error was then the debug output itself, which was pointing to the wrong memory address. Thanks rodrigo, since your answer lead to solving the problem: accepted. Thank you for your help and patience.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload