ctypes使用

ctypes是python下的一个可以链接c/c++的一个库。

可以将C函数编译成动态链接库, 即window下的.dll文件或者是linux下的.so文件.

可以调用c/c++,做一些python不能做的事情。例如对硬件操作,快速计算,操作内存。

对串口操作:


import platform
from ctypes import *
 
if platform.system() == 'Windows':
    libc = cdll.LoadLibrary('uart.dll')
elif platform.system() =='Linux':
    libc = cdll.LoadLibrary('uart.so')
    
libc.printf('简单!\n')

调用c语言操作设备:

定义c库

#include <stdio.h>
#include "device_deader.h"

int i2c_init(void)
{
 return true;
}

int i2c_read(char addr, char length)
{

}

int i2c_write(char addr, char length)
{

}

在linux环境下编译为动态链接库:gcc i2c.c -fPIC -shared -o i2c.so

现在就可以通过ctypes调用

from ctypes import *

#i2c_device = CDLL("./i2c.so")
i2c_device = ctypes.cdll.LoadLibrary("./i2c.so")
result = i2c_device.i2c_init()
read = i2c_device.i2c_read(0x10,1)
result = i2c_device.i2c_write(0x10,1)
发布了17 篇原创文章 · 获赞 2 · 访问量 2090

猜你喜欢

转载自blog.csdn.net/wun123/article/details/96430406