简体   繁体   中英

Wrong values passed as parameter to C library using SWIG

Following my three previous posts , I can now pass a managed array of struct to my wrapped method. Here is an extract from the files:

// packer.i
typedef struct {
  int width; // input
  int height; // input
  frame_t view; // output
  frame_t dest; // output
} image_t;

CSHARP_ARRAYS(image_t, image_t)
%apply image_t INOUT[] { image_t *images }

int pack(image_t *images, int nb_images, parameters_t params);

Which generates a function with this signature:

// packer_cs.cs
public static int pack(image_t[] images, int nb_images, parameters_t arg2)

Which I call like this:

// Program.cs
var files = Directory.GetFiles("./images");
var images = new image_t[files.Length];
for (var f = 0; f < files.Length; f++)
{
    using (var imgInfo = Image.FromFile(files[f]))
    {
        var imgStruct = new image_t()
                        {
                            width = imgInfo.Width,
                            height = imgInfo.Height,
                            dest = new frame_t(),
                            view = new frame_t()
                        };
        images[f] = imgStruct;
    }
}
var result = packer_cs.pack(images, images.Length, new parameters_t());

All is well and done, but when I run the pack() method, I have a protected memory access problem ( System.AccessViolationException ). Thankfully I have access to the source code of the C library, and Visual Studio automagically opens it for debugging and stepping through as soon as I enable unmanaged code debugging.

So, if I add a breakpoint at the start of the pack() function, and I use a watch to check images[x] , I can see that the width and height values have nothing to do with what is provided (sometimes it's even 0 or negative). What's going on ? If I inspect my managed array on the C# side, the values are correctly stored and retrieved. Why doesn't C get the right values ? The other parameters (nb_images and params) don't have any problem.

Thank you !

Do the following:

  1. Check that images[f].width and height have the values you expect
  2. If yes, then check the SWIG-generated code to verify that those fields are properly copied.
  3. If you can't spot any problem by looking at the code, you should break on packer_cs.pack and use the debugger to look at the wrapper code that copies the C# array to the C++ array, see what is wrong.

It is probably something in the typemaps that is incorrect. Once you know what that is, you can copy the typemaps code from SWIG source (the csharp_array.i file) to a new typemap in your .i and fix as required.

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