The problem is the marshalling of the null-terminated C strings. You cannot expect the p/invoke marshaller to deal with those in a function return value. The struct needs to be declared like this:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct teststruct
{
public byte acharacter; // don't use C# char which is 2 bytes wide
public int anumber;
public IntPtr astring;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public char[] anarray;
public IntPtr conststring;
}
You'll need to use Marshal.PtrToStringAnsi
to extract the contents of the C strings.
As a more general piece of advice, passing large structs as function return values is a bad idea. There is no single generally accepted ABI for doing that. Different compilers handle this in different ways. Better is to allocate the struct in the calling code, and pass its address. Like this:
__declspec(dllexport) void TestDLL(teststruct *ts)
{
ts->... = ...;
...
}
And on the C# side:
[DllImport(...)]
public static extern void TestDLL(out teststruct ts);
In fact, it would not surprise me if the struct that you are trying to work with cannot be marshalled as a return value. You really should pass it as an out
parameter.