通过ctypes在C函数中调用python函数

在C语言中定义如下函数

//定义函数指针类型
typedef void(*Callback)(int a);

XLIB void TestCallback(int *arr, int size, Callback call)
{
    for (int i = 0; i < size; i++)
    {
        call(arr[i]);
    }
}

python代码如下 !FILENAME testctypes.py

print("Test CTypesfunction")
from ctypes import *

#回调函数类型 返回值void 参数c_int
FUNT = CFUNCTYPE(None, c_int)

#回调函数
def callback(a):
    print("Py a = ",a)

try:
    lib = CDLL("Testctypesfunction")
    # 传递的数据
    arr = [1, 3, 55, 11, 34]
    ArrType = c_int * len(arr)
    # Ctype的数组对象
    carr = ArrType(*arr)
    lib.TestCallback.argtypes = (ArrType, c_int, FUNT)
    lib.TestCallback(carr,len(arr),FUNT(callback)) 


except Exception as ex:
    print("testctyeps error",ex)

# 等待用户输入,程序不退出
input()

运行结果如下

Test CTypesfunction
Py a =  1
Py a =  3
Py a =  55
Py a =  11
Py a =  34
© liangqi all right reserved,powered by Gitbook文件修订时间: 2019-06-01

results matching ""

    No results matching ""