[Tech] Python Call C function

来源:互联网 发布:爱奇艺会员淘宝暗语 编辑:程序博客网 时间:2024/06/16 06:34

Python Call C function, it’s funny for me to call some C function in Python. Because with these code , I can integrate python and C more easyly. Now lets see how to integrate Python and C:
Firstly, We build a C file to call python script with Python C API:

#include <Python.h>#include <string>#include <stdio.h>int Test(){    PyRun_SimpleString("import sys");     PyRun_SimpleString("sys.path.append('')");    PyObject * pMod = PyImport_ImportModule("myadd");    if(!pMod) {        printf("Error to import add module!\n");        return 2;    }       PyObject * pFun = PyObject_GetAttrString(pMod, "add");    PyObject * pParm = PyTuple_New(2);    PyTuple_SetItem(pParm, 0, Py_BuildValue("i", 200));    PyTuple_SetItem(pParm, 1, Py_BuildValue("i", 400));    PyObject * pRetVal = PyEval_CallObject(pFun, pParm);    int iRetval = 0;    PyArg_Parse(pRetVal, "i", &iRetval);    printf("result: %d\n", iRetval);    return 1;}int main(int argc, char ** argv) {    Py_Initialize();    Test();    Py_Finalize();    return 1;}
#include <Python.h>#include <string>#include <stdio.h>using std::string;static PyObject* GetName(PyObject *self, PyObject *args){    const char *url;    std::string sts;    if (!PyArg_ParseTuple(args, "s", &url))        return NULL;    printf("The args passed by the script: %s\n", url);    return Py_BuildValue("s", "Success!");}static PyMethodDef TestLibMethods[] = {       {"GetName", GetName, METH_VARARGS},       {NULL, NULL},};extern "C" void initlibforpython(){    PyObject *m, *d;    m = Py_InitModule("libforpython", TestLibMethods);    d = PyModule_GetDict(m);}
import libforpythondef add(p, a):     t = libforpython.GetName("ASDASDF")    print(t)    return p+a

Let me explain the three segments of the code:

The first of the segments of the code is the main part, It is the enterance of the program in this part of function, we call the python through the methon Python.h provided. before we call the python we should initial the envirement of Python by Py_Initialize(); function call. then we can call the method we need. the programming of C passed 2 arguments to Python scrip.

The second of the segments, is the C code build Python Interface to Python Script, so Python can call the function written by C. the array named TestLibMethods as type of PyMethodDef is the index of the functions which are exposed to Python Script. In this module, you should write a function call init*() for the python, because, when python script want to call these function python should import all the module, when the python import the library the init*() function call should be called. this function is very important to the module. and all the initial works will be done in this function include regist the PyMethodDef table.

The last part of the code is Python Script, in this example the script is so simple as just call the lib provided by the second segment. so when the first part of these code call the third part of the code ,then the third part will call the second part. finally all the code will be co-work together.

This is just a simple example, so it just include less function of python API and C code. If you want to learn much, you should go to the Python official site here.

source:
http://gordenfl.blog.163.com/blog/static/13633062009920114120325/

0 0
原创粉丝点击