I have the following structs defined in my c dll:
typedef struct {
char Name[10];
char Flag[10];
} CountryData;
typedef struct {
int NumElements;
TrackData Elements[1000];
} CountryArray;
Which is exposed like so:
__declspec( dllexport ) CountryArray* _cdecl GetAllCountries()
{
CountryArray fakedata;
CountryData fakecountry = CountryData();
strcpy_s(fakecountry.Name, "TEST");
strcpy_s(fakecountry.Flag, "TEST");
fakedata.Elements[0] = faketrack;
fakedata.NumElements = 1;
return new CountryArray(fakedata);
}
Now in c# I have these structs defined:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct COUNTRY
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string Name;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string Flag;
}
[StructLayout(LayoutKind.Sequential)]
public struct COUNTRY_ARRAY
{
public int NumElements;
public IntPtr Elements;
}
And I access it through this import:
[DllImport("Countries.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "?GetAllCountries@@YAPAUCountryArray@@XZ")]
public static extern IntPtr GetAllCountries();
And finally I attempt to marshal the data like so:
IntPtr countryPtr = Natives.GetAllCountries();
Natives.COUNTRY_ARRAY countries = (Natives.COUNTRY_ARRAY)Marshal.PtrToStructure(countryPtr, typeof(Natives.COUNTRY_ARRAY));
for (int i = 0; i < countries.NumElements; i++)
{
IntPtr iptr = (IntPtr)(countries.Elements.ToInt32() + (i * Marshal.SizeOf(typeof(Natives.COUNTRY))));
try
{
//fails here
Natives.COUNTRY country = (Natives.COUNTRY)Marshal.PtrToStructure(iptr, typeof(Natives.COUNTRY));
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
The marshalling of the country is where I receive this error:
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at System.Runtime.InteropServices.Marshal.PtrToStructureHelper(IntPtr ptr, Object structure, Boolean allowValueClasses)
I've tried modifying the size of the COUNTRY struct and changing the charset but still get this error. I'm completely stuck, what can be the issue here?