4

Given the following SWIG interface definition:

%module example

%include "arrays_csharp.i"
%apply int INOUT[] {int *x}

struct mystruct
{
        int *x;
}

SWIG produces the following (snippet from mystruct.cs):

  public int[] x {
    set {
      examplePINVOKE.mystruct_x_set(swigCPtr, value);
    } 
    get {
      IntPtr cPtr = examplePINVOKE.mystruct_x_get(swigCPtr); // Error 1
      SWIGTYPE_p_int ret = (cPtr == IntPtr.Zero) ? null : new SWIGTYPE_p_int(cPtr, false);
      return ret; //Error 2
    } 
  }

This causes VS2010 to produce the following two errors:

Error   1   Cannot implicitly convert type 'int[]' to 'System.IntPtr'   
Error   2   Cannot implicitly convert type 'LibLinear.SWIG.SWIGTYPE_p_int' to 'int[]'

at the areas marked in the above code snippet.

I developed the interface according to http://www.swig.org/Doc1.3/CSharp.html#CSharp_arrays_pinvoke_default_array_marshalling , which only talks about functions but not structures. Should the interface definition for structure members be different?

saffsd
  • 23,742
  • 18
  • 63
  • 67

1 Answers1

0

It might be that it can't handle an array of structs because of the unknown size/layout in memory (which is not a problem for int/double/etc...). Is it possible for you to use a vector of structs instead? I've had no problems passing vectors of structs or custom objects by simply including std_vector.i and relevant typemaps, eg:

%include "std_vector.i"

%typemap(MyClassVec) std::vector<MyClass>;
Tim B
  • 3,033
  • 1
  • 23
  • 28