使用cython从C调用python导入python文件 [英] Call python file with python imports from C using cython

查看:92
本文介绍了使用cython从C调用python导入python文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题基于这一个,但带有一个捻.我想使用cython编译一个python函数,然后在C中调用它.在这种简单的情况下,它可以工作,但是当我尝试从我的python代码中导入另一个python模块时,它不起作用.

This question is based on this one, but with a twist. I want to compile a python function using cython, then call it in C. In this simple case, it works, but when I try to import another python module from my python code, it doesn't work.

world.pyx

world.pyx

def world():
    return 10

hello.pyx

hello.pyx

import world

def hello():
    ret = 5 + world()
    return ret

cdef public int call_hello():
    return hello()

main.c

#include <Python.h>
#include "hello.h"

int main() {
  Py_Initialize();
  PyInit_hello();
  int v = call_hello();

  printf("the value is %d\n",v);

  Py_Finalize();
  return 0;
}

cython -3 --force world.pyx hello.pyx
clang -c world.c hello.c main.c -I/Users/aneben/.pyenv/versions/3.6.1/Python.framework/Versions/3.6/include/python3.6m -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
clang -L/Users/aneben/.pyenv/versions/3.6.1/Python.framework/Versions/3.6/lib/python3.6/config-3.6m-darwin -lpython3.6m -ldl -framework CoreFoundation world.o hello.o main.o  -o main

如果我只是将 world 函数移到 hello.pyx 中,那么它将正常工作.但这在导入时不起作用.

If I simply move the world function into hello.pyx, then it works fine. But it doesn't work as written when I import it.

./main

NameError: name 'hello' is not defined
Exception ignored in: 'hello.call_hello'

推荐答案

一种解决方案似乎是在主函数中添加对 PyInit_world(); 的调用.Cython将此功能添加到 world.c 中,即使在这种情况下它不会生成头文件,因此我们得到警告,但它可以工作.

One solution seems to be to add a call to PyInit_world(); in the main function. Cython adds this function to world.c, even though in this case it does not generate a header file, so we get a warning, but it works.

有没有办法让 hello.c 自动调用 PyInit_world(),所以 main.c 不需要知道关于那个?这样,C include层次结构将镜像python.

Is there a way to have hello.c call PyInit_world() automatically, so that main.c doesn't need to know about that? In that way, the C include hierarchy would mirror the python one.

这篇关于使用cython从C调用python导入python文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆