0

I asked a similar question yesterday, but this is slightly different. I am having problems passing arrays of struct from c# to c++, and getting this back again.

Here is the c++ code. Firstly, the struct:

struct Tri
{
   public:
     int v1, v2, v3;
}

and now the c++ dll part:

extern "C" __declspec(dllexport) void Dll_TriArray(Tri *tri)
{
   int num = 10;
   tri = new Tri[num];

   for (int i = 0; i < num; i++)
   {
      tri[i].v1 = i + 5;
      tri[i].v2 = i + 10;
      tri[i].v3 = i + 25;
   }
}

and here's the c# code, again starting with the struct:

[StructLayout(LayoutKind.Sequential)]
public struct Tri
{
   public int v1, v2, v3;
}

public class Testing
{
   [DllImport("testing.dll")]
   static extern void Dll_TriArray(out Tri[] tryArray);

   public GetTriArray()
   {
      Tri[] triArray;
      Dll_TriArray(out triArray);
   }
}

So the triArray i get when calling the GetTriArray method will come back as null. I have thought about passing an IntPtr in as the argument, but then how does one marshal an intptr into/from an array of struct?

BTW - at this stage, i'm not interested in memory leaks.

3
  • BTW - at this stage, i'm not interested in memory leaks. That's a dangerous stance to take at any point in your development. Commented Jun 14, 2013 at 10:32
  • How should the CLR know the size of the array? Commented Jun 14, 2013 at 10:32
  • This might be of interest:stackoverflow.com/questions/1086294/… Commented Jun 14, 2013 at 10:33

1 Answer 1

1

I'm not an expert (by any means) in C# but the C++ part gets passed a pointer to Tri-struct, which in C++ can be used like an dynamic array you allocate and fill that correctly but you don't have a way to get it back, because from C-perspective you'd need to modify the caller's (C#) pointer but you only get a copy and not a reference to the original.

In C++ the closest thing to what you are tying to do, would be to change the prototype to void Dll_TriArray(Tri *&tri) (call by ref, not call by copy) but I'm not sure how to interface that with C# (probably Dll_TriArray(ref triArray); ).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.