本文的使用建立在前两篇文章内容之上,链接如下:
【python环境下调用C代码—编译】学习笔记
【python环境下调用C代码—附件】学习笔记
实例化cffi
import cffi
ffi = cffi.FFI() # 实例化ffi
from _test_cffi import ffi, lib # 包含 ffi , 库
使用C的数据类型
string_data = ffi.new("char[]", b"hello") # 使用 char 类型, 数组
# "Process finished with exit code -1073741819 (0xC0000005)" 为错误使用指针
num = ffi.new("int *", 520) # 使用 指针
struct_data = ffi.new("struct_test *", [1, 2]) # 使用编译通过的结构体
调用函数
lib.PrintTest()
使用回调
先为回调函数赋予内容(此处需要用到修饰器 @ ),再将回调函数作为参数传给调用函数
# 定义回调函数
@ffi.callback("void (*CallBack)(int num)")
def PrintNum(num):
print(f"\r\nThe Num Is: {num}", num)
# 将回调函数作为参数传给调用函数
lib.call(PrintNum, 520)
完整代码如下:
# -*- coding: utf-8 -*-
import cffi
ffi = cffi.FFI() # 实例化ffi
from _test_cffi import ffi, lib
string_data = ffi.new("char[]", b"hello") # 使用C的数据类型
print("字符串长度:", len(string_data), " 字符串第一个字符:", string_data[0], " 字符串内容:", ffi.string(string_data))
num = ffi.new("int *", 520) # 指针
lib.HelloWorld(num) # 调用C函数
struct_data = ffi.new("struct_test *", [1, 2]) # 使用库里的数据类型
print(f"struct_data.y: {struct_data.y}")
lib.PrintTest()
# 定义回调函数
@ffi.callback("void (*CallBack)(int num)")
def PrintNum(num):
print(f"\r\nThe Num Is: {num}", num)
# 将回调函数作为参数传给调用函数
lib.call(PrintNum, 520)
运行后结果如下:
字符串长度: 6 字符串第一个字符: b'h' 字符串内容: b'hello'
520.Hello World
struct_data.y: 2
Your_name666
The Num Is: 520 520