在Cython documentation中,可以使用扩展.pxd
将纯python脚本编译为C库。
但是我不能按原样使用该示例。我的最终目标是直接从python模块中将函数和类作为C对象调用(这意味着不在C程序中使用python会话)。
文件为:
foo.py
from __future__ import print_function
def myfunction(x, y=2):
a = x - y
res = a + x * y
print("myfunction:result is:", res)
return res
def _helper(a):
res = a + 1
print("_helper:result is:", res)
return res
class A:
def __init__(self, b=0):
self.a = 3
self.b = b
def foo(self, x):
print(x + _helper(1.0))
foo.pxd
cpdef int myfunction(int x, int y=*)
cdef double _helper(double a)
cdef class A:
cdef public int a, b
cpdef foo(self, double x)
main.c
#include <Python.h> //needed
#include <foo.h>
int main(void){
Py_Initialize(); //Needed!
initfoo(); //Needed! called PyInit_hello() for Python3
_helper(3.);
myfunction(3,2);
A a;
a.foo(3.);
Py_Finalize(); //Needed!
}
Makefile
CC := gcc
# CFLAGS := $(shell python-config --cflags) -c -fPIC -g -ggdb -O0 -D_DEBUG
CFLAGS := -c -fPIC -g -ggdb -O0 -D_DEBUG -Wall #-Werror
LDFLAGS:= -shared
# CLIBS := -L$(shell python-config --prefix)/lib $(shell python-config --ldflags)
CLIBS := -L/usr/local/python-gnu-2.7.8/lib -lpython2.7
RM := rm -f
CYTHON := cython
INCLUDE_PATH := -I/usr/local/python-gnu-2.7.8/include/python2.7
.PHONY: all clean
NAME := main
CYTHONSRC := foo.py
CYTHONOBJS := $(CYTHONSRC:.py=.so)
LIBS := libfoo.so
SRCS := #main.c # $(wildcard *.c)
OBJS := $(SRCS:.c=.o)
all: $(NAME)
lib: $(LIBS)
#
libfoo.so: foo.o
$(CC) -I. -L. $(LDFLAGS) $(CLIBS) -o $@ $^
#
# link the .o files into the target executable
#
$(NAME): $(LIBS) $(OBJS)
$(CC) $(LDFLAGS) $(CLIBS) $(INCLUDE_PATH) $(CFLAGS) -I. -L. -lfoo -o $@ $@.c
#
# compile the .c file into .o files using the compiler flags
#
%.o: %.c
$(CC) $(CFLAGS) $(INCLUDE_PATH) -I. $<
%.c: %.py
python -m cython $<
# $(CYTHON) -o $@ $<
clean:
$(RM) $(CYTHONSRC:.py=.c)
$(RM) $(CYTHONSRC:.py=.h)
$(RM) $(CYTHONSRC:.py=.o)
$(RM) $(LIBS)
$(RM) main
编辑: 但是make会出现以下错误:
main.c:10:5: error: unknown type name 'A'
A a;
^
main.c:11:6: error: request for member 'foo' in something not a structure or union
a.foo(3.);
^