I want to transfer a struct, containing structs, in C to python, using cpython.
//main.c
#include <Python.h>
struct properties {
struct position
double velocity;
}
struct position{
double rx;
double ry;
double rz;
}
struct velocity{
double vx;
double vy;
double vz;
}
void main(int argc, char** argv){
Py_Initialize();
struct properties pr;
position po = &pr.position;
velocity v = &pr.velocity;
_Py_fopen("f.py", "r+");
Py_Finalize();
}
#f.py
#import numpy as np
#pr = properties()
#po = pr.po
#v = pr.v
#poabs = np.abs(po.rx + po.ry + po.rz)
How can I manipulate the structs in a python file?
The only way I can think of is to transfer every variable individually,
//main.c
...
PyObject* rx = po.rx;
...
write getter methods for each variable according to https://docs.python.org/3/extending/embedding.html (1.4.)
//main.c
static PyObject* emb_getrx(PyObject *self, PyObject *rx)
{
return PyFloat_FromDouble(rx);
}
and embed each getter method
//main.c
static PyMethodDef EmbMethods[] = {
{"rx", emb_getrx, double, "Return rx."},
{NULL, NULL, 0, NULL}
};
static PyModuleDef EmbModule = {
PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods,NULL, NULL, NULL, NULL
};
to then import
#f.py
import emb
The real code contains many more structures and variables. Is there an easier way?
main.cand the link you provided, it looks like you're trying to embed Python in a C application, rather than creating a C extension module for CPython. Is that correct?