[Tech] Python Call C function

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 libforpython

def 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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值