2

So i'm trying to run a c++ native function in a dll from some c# code. And it works fine, however, when i use 'out' in my function call i get a memory access violation. This is what it looks like:

C# function

[DllImport(pluginName)]
public static extern IntPtr AddTriangleFixtuers(ShapeDef shapeDef, IntPtr toBody, ref Vector2 vertices, int triangleCount, Vector3 row1, Vector3 row2, out int fixtureCount);

...

int test = 1;
B2D.AddTriangleFixtuers(def, body.body, ref shapeTriangles[0], shapeTriangles.Length/3, firstRow, secondRow, out test);

C++ function

EXTERN_DLL_EXPORT b2Fixture* __stdcall AddTriangleFixtuers(ShapeDef shapeDef, IntPtr* toBody, b2Vec2* vertices, int triangleCount, b2Vec3 row1, b2Vec3 row2, int& fixtureCount) {
    fixtureCount = 0;

    b2Fixture* lastFixture = NULL;
    return lastFixture;
}

I've minimized the code to highlight the issue i'm running into. As soon as i try to set fixtureCount in the c++ code to anything i get the following error:

An exception of type 'System.AccessViolationException' occurred in Assembly-CSharp.DLL but was not handled in user code Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Enzign
  • 43
  • 5
  • 1
    You have to add the P/Invoke definition as well (the `[DllImport]` etc.). – Luaan Jan 15 '15 at 14:11
  • Sorry, i forgot to show that definition. Edited the question now. – Enzign Jan 15 '15 at 14:27
  • probably duplicated: stackoverflow.com/questions/26992178/c-sharp-dllimport-with-pointers – Maher Jan 15 '15 at 14:34
  • I don't think that is a duplicate. That question or answer doesn't help me i think. – Enzign Jan 15 '15 at 14:40
  • 2
    It is just the most likely way your C++ code will bomb because the [DllImport] declaration doesn't match the C++ function. It is *not* the last parameter that's the problem, it is the other ones. About all of them. It is *very* doubtful you can make this work with pinvoke, use C++/CLI instead. – Hans Passant Jan 15 '15 at 14:55
  • Hm, ok. It's wierd because i can use all the other parameters without problems. It's just when i use the last parameter that i get any problems. – Enzign Jan 15 '15 at 15:00

1 Answers1

0

Ok, i finally figured it out. It was row1 and row2 that caused the memory access violation. Even though i didn't use them in my c++ code. I had to send the x,y,z values in as floats to fix the crash.

So it was the conversion from Vector3 to b2Vec3 that was the problem. Like Hans mentioned in the comments, that the problem wasn't fixtureCount.

Enzign
  • 43
  • 5