【发布时间】:2014-03-31 01:08:03
【问题描述】:
我在我的 c dll 中定义了以下结构:
typedef struct {
char Name[10];
char Flag[10];
} CountryData;
typedef struct {
int NumElements;
TrackData Elements[1000];
} CountryArray;
这样暴露的:
__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);
}
现在在 c# 中我定义了这些结构:
[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;
}
我通过这个导入访问它:
[DllImport("Countries.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "?GetAllCountries@@YAPAUCountryArray@@XZ")]
public static extern IntPtr GetAllCountries();
最后我尝试像这样整理数据:
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());
}
}
国家的编组是我收到此错误的地方:
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)
我尝试修改 COUNTRY 结构的大小并更改字符集,但仍然出现此错误。我完全被卡住了,这可能是什么问题?
【问题讨论】:
标签: c# c++ c struct marshalling