python与c语言数据交互,python与c语言交互应用实例

1、python向c语言写数据

1) 先将接收端编译成一个共享链接库

gcc/arm-linux-gnueabihf-gcc -o bluetooth_proxy.so -shared -fPIC bluetooth_proxy.c

bluetooth_proxy.c

#include

structbluetooth_t{intstatus;char buf[128];

};int bluetooth_proxy_cb(structbluetooth_t bluetooth)

{

printf("bluetooth status:%d, buf:%s \n", bluetooth.status, bluetooth.buf);return 0;

}

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

bt_msg_send_simple.py

#!/usr/bin/python

importctypesfrom ctypes import *

classbluetooth(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= 555s.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

static PyObject *test(PyObject *self, PyObject *args){intarg1, arg2;if(!(PyArg_ParseTuple(args, "ii", &arg1, &arg2))){returnNULL;

}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

importtestprint test.test(1, 2) #输出 21

demo在github上

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值