Python脚本调用C函数,调用Python函数

时间:2014-11-18 19:41:04

标签: python c ctypes

我是普通的C用户,但对Python来说还是新手。

我有一个用C语言编写的库,用于执行我试图从Python脚本调用的计算。该库需要一些用户定义的例程,我试图允许使用Python脚本。

我遇到了一个问题,向我展示我不理解非常基本的东西。这是我无法运行的简单程序的代码。它应该在屏幕上打印7(2 + 5)的结果。

首先调用Python脚本test.py。它加载ctypes和库libfoo.so,并调用C例程c_do_work

from ctypes import cdll
lib = cdll.LoadLibrary('./libfoo.so')

print "Python 1: Going in..."
lib.c_do_work(2,5)

C函数c_do_work在库libfoo.so中定义,它具有单个模块test.c.此例程应运行Python脚本my_func.py,它定义函数find_sum。 Python解释器在这里初始化:

//gcc test.c -I/usr/include/python2.7/ -L/usr/lib/python2.7/ -lpython2.7 -lm -fPIC -c
//gcc -shared -Wl,-soname,libfoo.so -o libfoo.so  test.o
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>

void c_do_work(int a,int b)
{
    Py_Initialize();

    PyObject* main_module = PyImport_AddModule("__main__");
    PyObject* main_dict = PyModule_GetDict(main_module);

    FILE* file_1 = fopen("my_func.py", "r");
    PyRun_File(file_1, "my_func.py",Py_file_input,main_dict, main_dict);
    PyObject* expression = PyDict_GetItemString(main_dict,"find_sum");

    printf("C: calling Python function...\n");
    PyObject_CallFunction(expression,"ii",a,b);

    //Clean up
    fclose(file_1);
    Py_Finalize();
}

最后,Python脚本my_func.py:

def find_sum(a, b):
    print a+b

当我运行&#34; python test.py&#34;时,我在C函数的第二行出现了分段错误:

PyObject* main_module = PyImport_AddModule("__main__");

为什么会这样?如果我略微重写C例程,因此它是主要的,并直接运行该程序,我得到了所需的结果。问题似乎与让Python解释器调用初始化Python解释器的例程有关。

0 个答案:

没有答案