I am creating a python extension for some C functions that I have developed.
That code makes use of complex structures that we don't need to analyze from the python code so we are using pointers capsules to pass the structures from one funtion to another.
This is a simplification of a python extension that I am creating in C (here I use only a double instead of our structures):
#include "Python.h"
static PyObject *example2 (PyObject *dummy, PyObject *args)
{
PyObject *pymodel=NULL;
if (!PyArg_ParseTuple(args, "O", &pymodel))
return NULL;
double *numero;
if (!(numero = (double*) PyCapsule_GetPointer(pymodel, "DOUBLE"))) {
return NULL;
}
printf("Pointer %x and value %f\n",numero,*numero);
return Py_BuildValue("");
}
static PyObject* example (PyObject *dummy, PyObject *args)
{
double *numero;
double valnum = 6.0;
numero = &valnum;
printf("Pointer %x and value %f\n",numero,*numero);
PyObject * ret = PyCapsule_New(numero, "DOUBLE", NULL);
return ret;
}
/* Module method table */
static PyMethodDef LIBIRWLSMethods[] = {
{"example", example, METH_VARARGS, "descript of example"},
{"example2", example2, METH_VARARGS, "prediction using a trained model"},
{ NULL, NULL, 0, NULL}
};
/* module initialization */
PyMODINIT_FUNC initLIBIRWLS(void)
{
(void) Py_InitModule("LIBIRWLS", LIBIRWLSMethods);
}
After installing this extension with a setup.py file we call the functions from python:
import LIBIRWLS
myCapsule = LIBIRWLS.example()
LIBIRWLS.example2(myCalsule)
This is the standard output after running the python code:
Pointer b9c27b58 and value 6.000000
Pointer b9c27b58 and value 0.000000
The pointer address has been passed correctly but It has lost the value and we don't know the reason.