从cython传递3D numpy数组到C ++ [英] Passing 3D numpy array from cython to C++

查看:93
本文介绍了从cython传递3D numpy数组到C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近使用cython加快了应用程序的速度,现在很难将3D numpy数组从cython传递到C ++函数.我可以从python测试脚本中调用我的函数,但这是segfauls.当我自己测试C ++时,它不会.因此,我假设我在正确传递数组时做错了事.

I recently used cython to speedup an application, and now struggle with passing a 3D numpy array from cython to a C++ function. I can call my function from a python test script, but it segfauls. When I test my C++ on its own, it does not. Therefore, I assume that I do something wrong with passing the array correctly.

那里出了什么问题?

 >> python test_harvest.py   

   (100, 100) I twerk 
   [1] 6771 segmentation fault (core dumped)  python    test_harvest.py

logic.pyx

import cython

import numpy as np
cimport numpy as np

cdef extern from "fast_harvest.h":
    void start_harvest(int *** data , int x, int y, int t, int n)

def harvest(np.ndarray[int, ndim=3, mode="c"] data not None, 
            int goal_x, 
            int goal_y, 
            int mission_time, 
            int number_of_robots): 

    m, n, o = data.shape[0], data.shape[1], data.shape[2]

    assert m == mission_time
    assert n == number_of_robots
    assert o == 2

    start_harvest (<int ***> data.data,
                   goal_x, goal_y, 
                   mission_time, 
                   number_of_robots)

fast_harvest.cpp

#include <iostream>
#include <cstdio>
#include "fast_harvest.h"
#include "Harvester.h"

using std::cout;
using std::endl;

void start_harvest(int ***data, int x, int y, int mission_time, int number_of_robots) {
    Point p(x,y);
    p.dump();
    cout << "I twerk" << endl;

    for(int n = 0; n < number_of_robots; n++) {
        int xpos = data[0][n][0];
        int ypos = data[0][n][1];
        printf("(%d, %d)\n", xpos, ypos);
    }
}

test_harvest.py

import numpy as np

import fharvest.logic as fhl


ROBO_COUNT = 2
MISSION_TIME = 20

GOAL_X = 100
GOAL_Y = 100    

data = np.zeros([MISSION_TIME, ROBO_COUNT, 2], dtype=int)

data[0][0] = 0, 200
data[0][1] = 200, 0

fhl.harvest(data, GOAL_X, GOAL_Y, MISSION_TIME, ROBO_COUNT)

print(data)

推荐答案

我最终要做的是将1D数组传递给C ++,并为其编写了一个包装类,以实现从3D坐标到1D坐标的转换.我的实际程序具有其内部数据结构.完成工作后,我将包装器传递给主类,然后将其状态复制到包装的1D缓冲区中.

What I finally ended up doing was passing a 1D-array to C++, and wrote a wrapper class for it to make the transformations from 3D to 1D coordinates. My actual program had its internal datastructures. After finishing its work, I passed the wrapper to the main class and it copied its state over to the wrapped 1D buffer.

这篇关于从cython传递3D numpy数组到C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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