簡體   English   中英

將列表的列表從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]] 1、5、9 a = [[1, 5, 9], [4, 6, 7], [8, 2, 3]]作為a的參數傳遞C程序(通過argv),然后作為2D矩陣在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中使用相同的表示形式,並且可能要使用共享內存或文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM