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[];
}; int bluetooth_proxy_cb(struct bluetooth_t bluetooth)
{
printf("bluetooth status:%d, buf:%s \n", bluetooth.status, bluetooth.buf); return ;
}

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 * );
} 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

最新文章

  1. 用vue.js学习es6(一):基本工具及配置
  2. Lintcode 469. 等价二叉树
  3. loopback 03
  4. 如何将ToolBar 样式设置Title文字水平居中
  5. 图像金字塔及其在 OpenCV 中的应用范例(下)
  6. HDU 2196 求树上所有点能到达的最远距离
  7. EasyUI datetimebox设置默认值为当前时间
  8. bzoj1296
  9. Mybatis传参方式
  10. 零开始:NetCore项目权限管理系统:基础框架搭建
  11. 免费申请使用IBM Cloud Lite(轻量套餐) 续
  12. 从壹开始前后端分离 [ Vue2.0+.NET Core2.1] 二十一║Vue实战:开发环境搭建【详细版】
  13. ctf密码学习题总结
  14. 构建一个 预装 pm2 的 node 项目 docker 底包
  15. SVN分支与合并【超详细的图文教程】(转载)
  16. python-反射案例讲解
  17. 阿里云的免费型DV SSL证书
  18. 魔豆应用开发傻瓜书——helloworld
  19. ES Terms 聚合数据不确定性
  20. json字符串转JSONObject和JSONArray以及取值

热门文章

  1. 如意云路由刷PandoraBox
  2. node.js发http请求
  3. 02 java 程序环境
  4. Unity3D项目之 Survival Shooter 记录
  5. Unity3D 新版粒子系统 (Shuriken)
  6. 辛星和您一起解析PHP中的单例模式
  7. VC++为你的程序增加内存泄露检测
  8. python3----scrapy(笔记)
  9. 剑指 offer set 18 数组中只出现一次的数字
  10. Mybatis框架中Mapper文件传值参数获取。【Mybatis】