C ++和Python:将2D双指针数组从python传递并返回到c ++ [英] C++ & Python: Pass and return a 2D double pointer array from python to c++

查看:42
本文介绍了C ++和Python:将2D双指针数组从python传递并返回到c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将2D数组从Python传递到C ++函数,然后将相同类型,相同尺寸的数组返回给Python.我知道这个问题已经被问过几次了,但是我找不到与我问题相关的答案.对于我的问题,我必须使用双指针数组,并使函数返回双指针数组(如许多示例所示,不是 void ).

I want to pass a 2D array from Python to a C++ function and then return an array of the same type, same dimensions, to Python. I am aware this question has already been asked several times, but I haven't been able to find a relevant answer to my question. For my problem, I must use a double pointer array and have the function returning a double pointer array (not void as many examples show).

我的C ++函数是:

#include <stdio.h>      
#include <stdlib.h> 

extern "C" double** dot(double **a, int m, int n){

    double **arr = (double **)malloc(m * sizeof(double *)); 
    for (int i=0; i<m; i++) 
         arr[i] = (double*)malloc(n * sizeof(double));

    for (int i=0; i < m; i++){
        for (int j=0; j < n; j++){
            arr[i][j] = a[i][j];
            }
    }
    return arr;
}  

目前,我已经使用了 Ctypes .我知道我可以使用 Swig 界面,但是由于我不太了解它,我宁愿避免使用它.但是,我仍然愿意接受任何建议.我必须使用 Swig 的问题是,如果我没有记错的话,我必须使用 Typemap 来分解指针结构,这是一个部分,我不太了解.

For the moment, I have used Ctypes. I know I could use the Swig interface but I would prefer avoiding it given that I don't know it very well. However, I am still open to any suggestion. My problem if I had to use Swig is that, if I'm not mistaking, I would have to use a Typemap in order to decompose the pointer structure, and it's a part I don't understand very well.

我目前在Python中尝试过的是:

What I have tried for the moment in Python is:

import ctypes as c
import numpy as np

ty_ = np.ctypeslib._ctype_ndarray(c.POINTER(c.POINTER(c.c_double)), (3,3))
x = np.arange(9.).reshape(3,3)

_dll = ctypes.CDLL('./double_2D.so')

_foobar = _dll.dot
_foobar.argtype = type(y)
_foobar.restype = type(y)

d = _foobar(y, 3, 3) #I would like d to be a nice matrix like x 

我也尝试过

c.cast(_foobar(y,3,3), c.POINTER(c.POINTER(c.c_double)))

但以上示例均无效.因此,关于在 Swig 中定义 argtype restype Typemap 的代码段的任何建议都是很大的帮助.

But none of the examples above work. So therefore, any suggestion for defining the argtype or restype, or a snippet for Typemap in Swig would be of great help.

推荐答案

列出思想夫妇:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆