2

I have a C struct with a float* field. It's considered an array of floats which depict an image. The C struct is part of a library that I'm wrapping by means of SWIG. That pretty much works. I can import the module and create instances of that struct (and others).

The struct looks something like this:

struct MyStruct {
    int width;
    int height;
    float* data;
};

I would like to fill this array from my Python code like

import Foo

d = Foo.MyStruct()
d.data = numpy.zeros(640*480)

This does not work out of the box. I'm getting a TypeError stating:

in method 'MyStruct_data_set', argument 2 of type 'float *'

in a SWIG internal method called _swig_setattr_nondynamic

I suppose I'll have to do something with the pointer in order to make clear that it's a float array of arbitrary size.

What is it that I have to do, supposedly in the module .i file, to make the code above working?

/edit: as requested, the .i file is no more than this:

%module Foo
%{
#include <Foo.h>
%}

%include Foo.h

Pretty basic. I'm completely new to SWIG.

Hendrik Wiese
  • 2,010
  • 3
  • 22
  • 49
  • can you paste your .i file as well please? – Ahmed Masud Sep 20 '18 at 15:23
  • I'm massively rusty on this, but try [`__array_interface__['data']()`](https://docs.scipy.org/doc/numpy/reference/arrays.interface.html#__array_interface__) –  Sep 20 '18 at 15:27
  • JETM could you go a bit more into detail? That would be awesome. Where should I try that exactly? – Hendrik Wiese Sep 20 '18 at 15:32
  • Hm, [this](https://stackoverflow.com/questions/32692575/how-to-convert-numpy-ndarray-to-c-float) might be a better approach. –  Sep 20 '18 at 15:46
  • After all it doesn't *have* to be a numpy array. I'd be fine with it if it was a list(float). But that also doesn't work out of the box. I'll see what the numpy.i approach can do for me. Nevertheless, if you have any further advice, I'll be happy to hear from you! – Hendrik Wiese Sep 21 '18 at 07:28
  • 1
    It is not very elegant, but you could include `%include "carrays.i"`, `%array_functions(float, floatArray)` and populate your data from Python using `s = Foo.MyStruct()` and `s.data = Foo.new_floatArray(40)` and access the data using `Foo.floatArray.get_data(s.data,index)` and use `Foo.floatArray.set_data` for writing – Jens Munk Sep 21 '18 at 19:33

0 Answers0