1

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?

2
  • related reading struct in python from created struct in c Commented Apr 10, 2020 at 20:20
  • Based on your main.c and 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? Commented Apr 10, 2020 at 20:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.