Suppose I have a simple Python File like
myFile.py
class Bar():
def __init__(self):
self.foo = []
def add_to_list(self, elem):
self.foo.append(elem)
def return_first_value(self):
return self.foo[0]
How do I create this class in C as an object and manipulate it several times without destroying it? In Pseudo-Code:
pseudo_code
pyFile = import_file("myFile.py")
pyObject = create_class("Bar")
pyObject.add_to_list(2)
printf(pyObject.return_first_value()) // returns 2
pyObject.add_to_list(5)
printf(pyObject.return_first_value()) // still returns 2
I searched in the stackoverflow community and found various references to the Python/C API which helped me calling a method (e.g. here). But I am kind of stuck in creating an object and calling the method within.
Here is what I tried:
test.c
#include <Python.h>
#include <stdio.h>
int main() {
Py_Initialize();
// Import Module
PyObject* myModule = PyImport_ImportModule("myFile");
// Create object
PyObject* myClass = PyObject_GetAttrString(myModule, "Bar");
PyObject* object = PyObject_CallNoArgs(myClass); // I don't believe this creates the object of Bar
//Add number to list
PyObject* add = PyObject_GetAttrString(object,"add_to_list");
PyObject* args = PyTuple_Pack(1,PyFloat_FromDouble(2.0));
PyObject* result = PyObject_CallObject(add,args);
return 0;
}
Any help is very appreciated!