[英]Convert a ctypes int** to numpy 2 dimensional array
我有一個用SWIG包裝的c ++實現,並編譯成一個可供python使用的模塊。
我使用ctypes用ctype參數調用函數,int double等.my_function(ctype args)的輸出是一個int **,即它是一個多維數組。
如何將其轉換為python腳本中的2D numpy數組? 我一直在尋找ctypes指針,但到目前為止我沒有運氣。 我花了很多時間閱讀python和numpy的C-API與SWIG一起使用,並且在c ++方面實現返回一個numpy數組到目前為止一直非常難以完全失敗。
使用NumPy和numpy.i
,這很容易
接口頭
#pragma once
void fun(int** outArray, int* nRows, int* nCols);
履行
#include "test.h"
#include <malloc.h>
void fun(int** outArray, int* nRows, int* nCols) {
int _nRows = 100;
int _nCols = 150;
int* _outArray = (int*)malloc(sizeof(int)*_nRows*_nCols);
*outArray = _outArray;
*nRows = _nRows;
*nCols = _nCols;
}
SWIG接口頭
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "test.h"
%}
%include "numpy.i"
%init
%{
import_array();
%}
%apply (int** ARGOUTVIEWM_ARRAY2, int* DIM1, int* DIM2) {(int** outArray, int* nRows, int* nCols)}
%include "test.h"
類型ARGOUTVIEWM_ARRAY2
創建一個托管的NumPy數組,當在Python中銷毀NumPy對象時,會自動調用free。
如果您想使用Python C API自己創建包裝器,可以使用numpy.i
SWIG生成的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.