Structure array inside structure when passing reference to C++


M

Mikko Penkkimäki

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
 
Ad

Advertisements

N

Nicholas Paldino [.NET/C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top