C语言程序 c如何调用python程序

2025-10-01 21:16:04

1、ubuntu 14.04 linux c

gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2

Python 2.7.6

2、file 1 [python file]: math_test.py

def add_func(a,b):

    return a+b

def sub_func(a,b):

    return (a-b)

file 2 [c source file]: c_call_python.c

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include "python2.7/Python.h"

int main(int argc, char** argv)

{

    int arg0 = 0,arg1 = 0;

    if(argc == 3){

        arg0 = atoi(argv[1]);

        arg1 = atoi(argv[2]);

    }else{

    printf("please input 2 args!!\n");

    return -1;

    }

    Py_Initialize();

    if ( !Py_IsInitialized())

    return -1;

    PyRun_SimpleString("import sys");

    PyRun_SimpleString("sys.path.append('./')");

    PyObject *pModule;

    PyObject *pFunction;

    PyObject *pArgs;

    PyObject *pRetValue;

    pModule = PyImport_ImportModule("math_test");

    if(!pModule){

        printf("import python failed!!\n");

        return -1;

    }

    pFunction = PyObject_GetAttrString(pModule, "add_func");

    if(!pFunction){

       printf("get python function failed!!!\n");

       return -1;

    }

    pArgs = PyTuple_New(2);

    PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", arg0));

    PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", arg1));

    pRetValue = PyObject_CallObject(pFunction, pArgs);

    printf("%d + %d = %ld\n",arg0,arg1,PyInt_AsLong(pRetValue));

    Py_DECREF(pModule);

    Py_DECREF(pFunction);

    Py_DECREF(pArgs);

    Py_DECREF(pRetValue);

    Py_Finalize();

    return 0;

}

3、root@linux:~/code# gcc -o c_call_python c_call_python.c -lpython2.7

root@linux:~/code# ./c_call_python 12 15

12 + 15 = 27

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢