zoukankan      html  css  js  c++  java
  • python与c语言交互应用实例

    1、python向c语言写数据

    1) 先将接收端编译成一个共享链接库
    gcc/arm-linux-gnueabihf-gcc -o bluetooth_proxy.so -shared -fPIC bluetooth_proxy.c

    bluetooth_proxy.c

    #include <stdio.h>
    
    struct bluetooth_t{    
        int status;
        char buf[128];
    };
    
    int bluetooth_proxy_cb(struct bluetooth_t bluetooth)
    {
            printf("bluetooth status:%d, buf:%s 
    ", bluetooth.status, bluetooth.buf);
    
            return 0;
    }

    2)运行发送端python脚本即可将python数据发送到c语言接口函数。

    bt_msg_send_simple.py

    #!/usr/bin/python
    import ctypes
    from ctypes import *
    
    class bluetooth(Structure):
            _fields_=[('status',c_int),('buf',c_char * 128)]
    
    if __name__ == "__main__":
    
        func = ctypes.cdll.LoadLibrary("./bluetooth_proxy.so")
        func.bluetooth_proxy_init()
        s = bluetooth()
        s.status = 555
        s.buf = bytes('hello,world')
        func.bluetooth_proxy_cb(s)

    注意:如果python调用的函数参数仅仅是个简单的指针,可以不用映射。

    例如char *data;

    func.bluetooth_proxy_cb(data)

     2、python从c语言读取数据

    既然能调用c语言链接库函数参数来发送数据,接收数据也可以从通过c语言函数返回值传递了。

    python_data = func.bluetooth_proxy_cb(var)

     

    3、python的c语言拓展

    用c语言写好so,然后 import xxxx 来无缝结合

    test.c

    #include<Python.h>
    static PyObject *test(PyObject *self, PyObject *args){
        int arg1, arg2;
        if(!(PyArg_ParseTuple(args, "ii", &arg1, &arg2))){
            return NULL;
        }
        return Py_BuildValue("i",  arg1 + arg2 * 10);
    }
    
    static PyMethodDef  testMethods[] = {
        {"test", test, METH_VARARGS, "This is test"},
        {NULL, NULL}
    };
    
    PyMODINIT_FUNC inittest(){
        Py_InitModule("test", testMethods);
    }

    gcc -I /usr/include/python2.7/ -fpic --shared -o test.so test.c

    test.py

    import test
    print test.test(1, 2)   # 输出 21


    demo在github上

    https://github.com/zhoudd1/python_call_c

     

    python和C语言混编的几种方式

    http://www.cnblogs.com/Colin-Cai/p/7594551.html

  • 相关阅读:
    shiro源码篇
    python内置模块之collections(六)
    python之自然语言处理入门(一)
    python第三方库之numpy基础
    python算法之近似熵、互近似熵算法
    MongoDB之conf配置文件详解(五)
    MongoDB之主从复制和副本集(四)
    MongoDB之python简单交互(三)
    python设计模式之常用创建模式总结(二)
    python设计模式之单例模式(一)
  • 原文地址:https://www.cnblogs.com/dong1/p/8868334.html
Copyright © 2011-2022 走看看