python ctypes

 

Python–ctypes(数据类型详细踩坑指南)

使用

// main.c
int Add(int x, int y) {
    return x + y;
}

int GetArray(int a[], int index) {
    int len = sizeof(a) / sizeof(a[0]);
    for (int i = 0; i < len; ++i) {
        a[i] *= 2;
    }

    return a[index];
}

void SetPointer(int* a) {
    *a = 0xFFFF;
}

假设生成库main.so

函数

dll = cdll.LoadLibrary('main.so')

x, y = 1, 2
res = dll.Add(x, y)

数组

dll = cdll.LoadLibrary('main.so')

a = [1, 2, 3, 4, 5]

array = (c_int * 5)(*a)
res = dll.GetArray(array, c_int(1))
print(res)

指针

dll = cdll.LoadLibrary('main.so')

p = pointer(c_int(1))

dll.SetPointer(p)
print(p.contents)