WildCrustacean
WildCrustacean

Reputation: 5976

Weird data corruption behavior with p/invoke

I'm having a very strange problem with p/invoke in C#. The unmanaged function I am trying to call has quite a few arguments (23), some of which are float arrays. Unfortunately I can't post the real code, but originally I was passing the float arrays into the function that makes the p/invoke call, something like this:

public void func()
{
    float[] a = new float[257];
    float[] b = new float[257];
    float[] c = new float[257];
    float[] d = new float[257];

    callDll(a, b, c, d);
}

[DllImport(DllName, EntryPoint="dllfunc", CharSet = CharSet.Ansi)]
public static extern void dllfunc(ref float a, ref float b, ref float c, ref float d);

public void callDll(float[] a, float[] b, float[] c, float[] d)
{
    dllfunc(ref a[1], ref b[1], ref c[1], ref d[1]);
}

I know the way the arrays are passed is kind of strange, but this all worked fine. Then I decided to combine the float arrays into an object, so I changed it to something like this:

public class myObj
{
    float[] a;
    float[] b;
    float[] c;
    float[] d;
}

public void func()
{
    myObj m = new myObj();

    callDll(m);
}

[DllImport(DllName, EntryPoint="dllfunc", CharSet = CharSet.Ansi)]
public static extern void dllfunc(ref float a, ref float b, ref float c, ref float d);

public void callDll(myObj m)
{
    float[] a = new float[257];
    float[] b = new float[257];
    float[] c = new float[257];
    float[] d = new float[257];

    dllfunc(ref a[1], ref b[1], ref c[1], ref d[1]);

    m.a = a;
    m.b = b;
    m.c = c;
    m.d = d;
}

This runs once, and then crashes on every subsequent call with an error about Attempted to read or write protected memory. This is often an indication that other memory is corrupt. The odd behavior does seem like some sort of memory corruption issue, but I don't understand at all how changing the argument list for the function that wraps the p/invoke call could have this sort of effect. Does anyone have any ideas?

UPDATE: I rearranged the arguments some more and this problem seems to have gone away. It must have been something the unmanaged code was doing, I'm not sure what. I voted to close this question since it seems to have been a localized problem.

Upvotes: 0

Views: 268

Answers (1)

Yaur
Yaur

Reputation: 7452

off by one? should

dllfunc(ref a[1], ref b[1], ref c[1], ref d[1]);

be

dllfunc(ref a[0], ref b[0], ref c[0], ref d[0]);

Upvotes: 1

Related Questions