Passing a C pointer around with the Python/C API

后端 未结 2 714
清酒与你
清酒与你 2020-12-19 00:24

I\'m new to the Python/C API ... I\'m trying to add new functionality to my C program, wherein I can embed python into it and simultaneously extend functionality so that the

2条回答
  •  [愿得一人]
    2020-12-19 01:08

    Assuming that you want some backwards compatibility, you want to use PyCObjects: http://docs.python.org/c-api/cobject.html

    If you only want to use python 3, you can use a PyCapsule: http://docs.python.org/c-api/capsule.html

    Basically the PyCObject stuff converts your opaque pointer into a PyObject that you can pass around within python and when you get back into C with one, you can unwrap it and use it.

    PyCapsules are pretty similar except they add a few features, the main one being that they allow you to store multiple pointers in the Capsule, so it's basically a dict.

    In your specific case, where you add the pointer, you'll just want to do this (error checking and destruction code removed):

    PyObject *pystate = PyCObject_FromVoidPtr(State, NULL);
    PyObject *dict = PyModule_GetDict(module);
    PyDict_SetItemString(dict, "CStateObject", pystate);
    
    # To retrieve it from self (assuming that it is an object)
    PyObject *pystate = PyObject_GetAttrString(self, "CStateObject");
    State *state = (State *)PyCObject_AsVoidPtr(pystate);
    

提交回复
热议问题