Structure array inside structure when passing reference to C++

Structure array inside structure when passing reference to C++

Post by Mikko Penk » Thu, 30 Oct 2003 23:57:45


I have a struct in C#-project and C++-project. I use the struct in C# but it
has to be filled in C++.

I know that arrays work like this:

In C++ code:

struct teststruct {
char str[100];
float myvar[2];
};

CPPPROJECTDLLDECL int DLLCALL callteststruct(teststruct *data) {
strcpy(data->str, "hello");
data->myvar[0] = 123.45f;
data->myvar[1] = 543.21f;
return 0;
}

In C# code:

using System.Runtime.InteropServices;

[Serializable()]
[StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
public struct teststruct {
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=100)]
public string str;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=2)]
public float[] myvar;
};

[DllImport("CppProject.dll")]
static public extern unsafe int callteststruct(ref teststruct data);

private void Page_Load(object sender, System.EventArgs e)
{
teststruct data = new teststruct();
callteststruct(ref data);
}


Now I need to add a structure array inside the "teststruct". It should look
something like this in C++:

struct teststruct2 {
int intvalue;
int anotherintvalue
char text[100];
}

struct teststruct {
char str[100];
float myvar[2];
teststruct2 teststruct2array[100];
};

But how to do it in C#?
I really would appreciate some help.
Thanks.

Mikko
 
 
 

Structure array inside structure when passing reference to C++

Post by Nicholas P » Fri, 31 Oct 2003 00:08:57

Mikko,

You would do it the same way. First, declare the teststruct2 structure,
like so:

[StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
struct teststruct2
{
int intvalue;
int anotherintvalue
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=100)]
char text[100];
}

Then alter your definition of teststruct like so:

[StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
public struct teststruct
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=100)]
public string str;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=2)]
public float[] myvar;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=100)]
public teststruct2 teststruct2array[];
}

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- XXXX@XXXXX.COM



it
look