Python C

2018-01-30 language python c/cpp

C 调用 Python 函数

#include <Python.h>

int main()
{
        PyObject * module, *func, *result;

        Py_Initialize();
        if (Py_IsInitialized() == 0) {
                printf("init error\n");
                return -1;
        }
        PyRun_SimpleString("import sys");
        PyRun_SimpleString("sys.path.append('./')");

        module = PyImport_ImportModule("foobar");
        if (module == NULL) {
                printf("Cant open python file!\n");
                return -2;
        }

        func = PyObject_GetAttrString(module, "foobar");
        result =  PyObject_CallFunction(func, "i", 2);
        if (result == NULL) {
                printf("Invoke foobar() function failed\n");
                return -3;
        }
        printf("foobar() return: %s\n", PyString_AsString(result));

        Py_Finalize();
}

然后通过 gcc -Wall -I/usr/include/python2.7 -lpython2.7 foobar.c -o foobar 编译。

其中 Python 脚本 foobar.py 如下:

def foobar(s):
	print s
	return s