I want to implement a following Python function in a C extension module:
def value(x: Optional[int] = None) -> Optional[int]:
if x is None:
# act like a getter
return APIGetValue() # retrieve the value from an external library
# act like a setter
APISetValue(x) # pass the value to an external library
return None
Here is what I got so far:
static PyObject* MyLib_PyValue(PyObject *self, PyObject *args, PyObject *kwargs) {
static char *kwlist[] = { "x", NULL };
int x;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:value", kwlist, &x)) {
return NULL;
}
if (x == NULL) {
return PyLong_FromLong(APIGetValue());
}
APISetValue(x);
Py_RETURN_NONE;
}
Calling the function with args works, but when calling value()
as a getter, I get 1
instead of NULL
. How should I proceed? I'm not very familiar with Python's C API yet.