简体   繁体   中英

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. I am following some examples I have seen online to use 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:

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. '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. 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 ). I did not notice that swig adds the output array to the return list and just wants the size of the array passed in.

I changed the method definition to this:

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

and I changed the python call to be this:

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

This now works and returns the array of data I wanted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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