Python:将ndarray数据传递给C++

Python numpy库的ndarray数据结构使用很方便,这里记录一下如何将其传递给C/C++代码,
直接上答案:
使用到的库:ctypes

C++代码部分(toPython.cpp):

#include 

extern "C" void showNdarray(int* data, int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("data[%d][%d] = %d\n", i,j,data[i * rows + j]);
        }
    }
}

将C++代码编译成动态链接库:
g++ -o topython.so -shared -fPIC toPython.cpp

Python代码部分:

import ctypes
import numpy as np

# 加载动态库
lcpp = ctypes.cdll.LoadLibrary
cpplib = lcpp("./topython.so")

def transfer_array_to_cpp() :
    data = np.array([[1,2,3,4,5],
                     [2,4,6,8,0]])
    dataptr = data.ctypes.data_as(ctypes.c_char_p)
    rows, cols = data.shape
    # 调用C++函数,将ndarray数据传递给C++
    cpplib.showNdarray(dataptr, rows, cols)
    
if __name__ == '__main__' :
    transfer_array_to_cpp()

Python代码放在和C++链接库同一个目录下,运行即可:

data[0][0] = 1
data[0][1] = 0
data[0][2] = 2
data[0][3] = 0
data[0][4] = 3
data[1][0] = 2
data[1][1] = 0
data[1][2] = 3
data[1][3] = 0
data[1][4] = 4

你可能感兴趣的:(pythonc++)