I am trying to create a Cython shell so that I can invoke Python code with C. I am having problems importing as I would like the shell to be separate from the source code.
Below is the code below segfault when calling the imported function. If the code is written as a python module and imported through import, the program says that name ... is not defined. The problem does not occur when everything is in one file and there is no import (indeed, the code generated by Cython fails when cimporting). The code works fine when libcimpy.pyx is imported from another python script (either compiled into .so or live)
I have prepared a minimal example. This is far from the actual code, but it covers the principle.
cimpPy.pyx: python code example (converted to Cython)
cdef sum(a, b):
return a + b
cimpPy.pxd
cdef sum(a, b)
libcimpy.pyx (glue Cython code)
cimport cimpPy
cdef public int cSum(int a, int b):
return cimpPy.sum(a, b)
ci.c (the code we want to call cimpPy from)
#include <stdio.h>
#include <stdlib.h>
#include <Python.h>
#include "libcimp.h"
int main(int argc, char **argv) {
Py_Initialize();
initlibcimp();
int a = 2;
int b = 3;
int c = cSum(a, b);
printf("sum of %d and %d is %d\n", a, b, c);
Py_Finalize();
return 0;
}
Makefile
EXECUTABLE = ci
OBJS = ci.o
CC = gcc
CFLAGS = -g -I/usr/include/python2.7 -I$(shell pwd)
LINKER = g++
LDFLAGS = -L$(shell pwd) $(shell python-config --ldflags) -lcimp
.PHONY: clean cython
all: cython $(EXECUTABLE)
cython:
python setup.py build_ext --inplace
.c.o:
$(CC) $(CFLAGS) -c $<
$(EXECUTABLE) : $(OBJS)
$(LINKER) -o $(EXECUTABLE) $(OBJS) $(LDFLAGS)
clean:
rm -rf *.o *.so libcimp.c libcimp.h core build $(EXECUTABLE)
setup.py
from distutils.core import setup, Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
extensions = [
Extension("libcimp", ["libcimp.pyx"])
]
setup(
name = "CIMP",
cmdclass = {"build_ext": build_ext},
ext_modules = cythonize(extensions)
)
What I intend to achieve is the ability to connect Python code to a larger C system. It is assumed that users will be able to write Python themselves. C code is a modeling mechanism that can work with agents in the environment. The idea is that the behavior of agents and the environment can be specified in python and passed to the engine for evaluation when necessary. A better analogy would be a map-reduction system where Python scripts are mappers. In this sense, I want to call Python with C, and not vice versa.
Converting everything to Cython while compelling would be a big task.
? python, ? .