将列表的列表从 Python 传递到 C 作为 uint64_t 矩阵

Pass list of list from Python to C as uint64_t matrix

如何将数字列表(C 中的uint64_t)例如:a = [[1, 5, 9], [4, 6, 7], [8, 2, 3]] 作为 C 程序的参数(通过 argv)传递,然后打印(或能够在 C 程序中以二维矩阵的形式访问该数据?

在我的 C 程序中,我使用 unint64_t 类型的非预定义大小矩阵 (uint64_t matrix[nrows][ncols])

有很多方法可以做到这一点,但最简单的可能就是先展平矩阵:

def flatten(a):
    yield len(a)
    cols = max(len(i) for i in a)
    yield cols
    for i in a:
        for j in i:
            yield j
        for j in range(0, cols - len(i)):
            yield 0

然后您可以使用它的结果将参数提供给您的 C 程序,然后您可以构建矩阵(需要 C99):

#include <stdlib.h>
#include <inttypes.h>

void load_matrix(uint64_t *matrix, char **p, int alen) {
    while (alen-- > 0)
        *matrix++ = atoi(*p++);
}

void do_work(uint64_t matrix[nrows][ncols], int nrows, int ncols) {
    ...
}

int main(int argc, char **argv) {
    int nrows = atoi(argv[1]), ncols = atoi(argv[2]);

    // check ncols and nrows and argc
    ...

    uint64_t *matrix;
    matrix = malloc(nrows * ncols * sizeof(*matrix));

    // check matrix isn't NULL
    ...

    load_matrix(matrix, argv + 3, nrows * ncols);
    do_work(matrix, nrows, ncols);
    ...
}

请记住,这只是一个示例,即 atoi 之类的内容不合适。

如果你想使用 C89,你需要处理一个平面数组,结果是一样的。

然而,如果矩阵很大,你真的不需要那样;你会以类似的方式序列化它(也许有更有效的实现),但你会想直接处理二进制数据,并通过共享内存、文件、套接字或管道将其传递给你的 C 程序,所以不需要进一步处理。

如果您正在处理一个非常大的数据集,那么您肯定希望在 Python 和 C 中使用相同的表示,并且您可能希望使用共享内存或文件。