简体   繁体   English

SWIG Python C ++输出数组给出“未知类型”错误

[英]SWIG Python C++ output array giving 'unknown type' error

I am trying to use swig to wrap some c++ code to pass a numpy array back to python. 我正在尝试使用Swig包装一些C ++代码以将numpy数组传递回python。 I am following some examples I have seen online to use numpy.i. 我正在跟踪一些我在网上看到的使用numpy.i的示例。 Here is what my code looks like. 这是我的代码的样子。

I am using this as the function definition in my class header file: 我将其用作类头文件中的函数定义:

bool grabFrame(int buf_size, unsigned char *buf);

In my interface file I have: 在我的界面文件中,我有:

/* File : OV4682Interface.i */
%module OV4682Interface
%include "std_string.i"

%{
    #define SWIG_FILE_WITH_INIT
    #include "OV4682FrameGrabber.h"
%}

%include "numpy.i"
%init %{
    import_array();
%}

%apply (int DIM1, unsigned char* ARGOUT_ARRAY1) {(int buf_size, unsigned char *buf)};

%include "../inc/OV4682FrameGrabber.h"

My Python code looks like this: 我的Python代码如下所示:

import numpy as np
import OV4682Interface as ov

width = 672
height = 380
buf_size = width*height*2

buf = np.zeros(buf_size, dtype=np.uint8)

grab = ov.OV4682FrameGrabber()
grab.grabFrame(buf)

When I run this I get the following error: 运行此命令时,出现以下错误:

Traceback (most recent call last): File "OV4682FrameGrabberTest.py", line 44, in grab.grabFrame(buf) File "/home/ubuntu/rgb_ir_frame_grabber/build/lib/OV4682Interface.py", line 117, in grabFrame def grabFrame(self, *args): return _OV4682Interface.OV4682FrameGrabber_grabFrame(self, *args) TypeError: Int dimension expected. 追溯(最近一次通话最后一次):在grab.grabFrame(buf)中的文件“ OV4682FrameGrabberTest.py”,第44行,在grabFrame def handleFrame中的文件“ /home/ubuntu/rgb_ir_frame_grabber/build/lib/OV4682Interface.py”,第117行(self,* args):返回_OV4682Interface.OV4682FrameGrabber_grabFrame(self,* args)TypeError:预期为Int尺寸。 'unknown type' given. 给出“未知类型”。

For some reason I am getting an error saying the type is unknown for the passed in array, but I have explicitly set the dtype to be np.uint8. 由于某种原因,我收到一个错误消息,说传入的数组的类型未知,但是我已将dtype显式设置为np.uint8。 I was wondering if anyone can point me to what I am doing incorrectly here as I am a bit stumped. 我想知道是否有人可以指出我在这里做错的事情,因为我有些困惑。

Looks like I did not look closely enough at the answer for this post ( SWIG+c+Python: Passing and receiving c arrays ). 看来我对这篇文章的答案不够仔细( SWIG + c + Python:传递和接收c数组 )。 I did not notice that swig adds the output array to the return list and just wants the size of the array passed in. 我没有注意到swig将输出数组添加到返回列表中,只是想要传入的数组大小。

I changed the method definition to this: 我将方法定义更改为:

void grabFrame(int buf_size, unsigned char *buf);

and I changed the python call to be this: 我将python调用更改为:

buf = grab.grabFrame(np.shape(buf)[0])

This now works and returns the array of data I wanted. 现在可以正常工作并返回我想要的数据数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM