PyObject_CallMethod with keyword arguments

后端 未结 2 1426
小鲜肉
小鲜肉 2021-02-15 12:47

I\'m trying to embed a Python (2.7) library in my C application and I\'m using the Python/C API to call Python code from C. I need to call a Python method that takes keyword arg

2条回答
  •  广开言路
    2021-02-15 13:38

    Tamas's answer will get the job done, but it will also leak memory. To avoid leaks, use

    PyObject *args = Py_BuildValue("(s)", "blahdy blah");    
    PyObject *keywords = PyDict_New();
    PyDict_SetItemString(keywords, "somearg", Py_True);
    PyObject *myobject_method = PyObject_GetAttrString(myobject, "do something");
    
    PyObject *result = PyObject_Call(myobject_method, args, keywords);
    Py_DECREF(args);
    Py_DECREF(keywords);
    Py_DECREF(myobject_method);
    
    // Do something with the result
    
    Py_DECREF(result);
    

    Of course, if there are any errors or exceptions in the Python code some of the PyObjects will be NULL and your program will probably crash. Checking for NULL results and/or using Py_DECREFX() can help you avoid this.

提交回复
热议问题