C++嵌入的Python PygGARPARTUPUPLE失败的字符串ARG

2024-09-28 20:15:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将嵌入式python添加到OpenGL/SDL应用程序中。 到目前为止,一切正常,比如通过SDL键盘事件输入一个字符串,然后用嵌入式python解释器执行它。 现在我要添加函数来调用C/C++函数,比如

void set_iterations(int c);

在python解释器上使用

^{pr2}$

整型参数的解析工作起来很有魅力

static PyObject* test_iterations(PyObject *self, PyObject *args) {  
    int iterations;
    PyArg_ParseTuple(args,"i",&iterations);
    set_iterations(iterations);

    return Py_None;
}

但当我尝试这个时:>>> test.addignore('something')

static PyObject* test_addignore(PyObject *self, PyObject *args) {

        char* ignorestring;
        //PyArg_ParseTuple(args,"s",ignorestring);
        PyArg_ParseTuple(args,"s",&ignorestring);
        add_global_ignore(ignorestring); // C function

        return Py_None;
}

Python给出了一个错误:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-3: invalid data

字符串应该是UTF-8,因为SDL被设置为从键盘获取UNICODE,其他一切都能完美地工作。在

有人知道我可能做错了什么吗?在

我还检查了传递给函数的args对象

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 << args_str << "\n";

它给了我这个:('somestring',)


解决方案: rodrigo指出的错误最初导致的是,我的调试代码应该将结果字符串打印为PyObject是错误的。但问题是我给解析器传递了错误的指针,导致内存中出现未定义的行为,因此我认为解析器就是问题所在。 最后一个解析器错误是调试输出本身,它指向错误的内存地址。 谢谢罗德里戈,因为你的回答导致了问题的解决:接受。谢谢你的帮助和耐心。在


Tags: 函数字符串pytest解析器错误argspyobject
1条回答
网友
1楼 · 发布于 2024-09-28 20:15:25

尝试:

static PyObject* test_addignore(PyObject *self, PyObject *args) {
    char* ignorestring;
    if (!PyArg_ParseTuple(args,"s", &ignorestring)) //Note the &
        return NULL;                                //Never ignore errors
    add_global_ignore(ignorestring);

    Py_RETURN_NONE;  //Always use helper macros
}

相关问题 更多 >