使用ctypes将2D整型数组从python传递到C++; 我试图通过Python将双数组的Its传递给C++库,使用cType。不幸的是,当我试图读取C++侧的数组条目时,我得到了一个Sebug。正确的方法是什么

使用ctypes将2D整型数组从python传递到C++; 我试图通过Python将双数组的Its传递给C++库,使用cType。不幸的是,当我试图读取C++侧的数组条目时,我得到了一个Sebug。正确的方法是什么,python,ctypes,Python,Ctypes,以下是我的python代码: #! /usr/bin/env python from ctypes import * # load the extension lib testLib = cdll.LoadLibrary('./libtest.so') # build adjacency matrix numNodes = 5 MatrixRowType = c_int * numNodes MatrixType = MatrixRowType * numNodes adj = MatrixT

以下是我的python代码:

#! /usr/bin/env python
from ctypes import *

# load the extension lib
testLib = cdll.LoadLibrary('./libtest.so')
# build adjacency matrix
numNodes = 5
MatrixRowType = c_int * numNodes
MatrixType = MatrixRowType * numNodes
adj = MatrixType()
for i in range(0, numNodes):
    for j in range(0, numNodes):
        adj[i][j] = c_int(0)
adj[0][0] = c_int(42)
for i in range(numNodes):
    print ' matrix value ', adj[i][0]
testLib.test_bridge(numNodes, adj)

这是我的C++代码:

#include <stdlib.h>
#include <iostream>
extern "C" {
    int test_bridge(int numNodes, int** adjacencyMatrix) {
       std::cout << " numNodes:" << numNodes << '\n';
       std::cout << " passed adjacency pointer " << adjacencyMatrix << '\n';
       std::cout << adjacencyMatrix[0][0] << std::endl;   // should be "42", instead we crash
    }
}
#包括
#包括
外部“C”{
内部测试电桥(内部节点,内部**邻接矩阵){

STD::CUT C++代码不使用连续的2D数组。它使用一个一维数组的代码< INT/INTCON>指针指向行,即<代码>邻接矩阵[0 ]。<代码> > <代码> int NoNoS< /Calp>元素数组。您需要在cType中创建这样的数组,或者修改C++代码以使用连续的2D数组。后者是有点麻烦的,因为数组作为指针指向第一个元素,并且机器代码没有被编译成处理动态数组。你最终会做数组运算,例如
adjacencyMatrix[i*numNodes+j]
。如果不清楚如何从现有的2D数组创建指针数组:
p_adj=(指针(c_int)*numNodes)(*adj)