[英]Marshaling a C++ two-dimensional fixed length char array as a structure member
我試圖調用一個非托管C ++函數,它具有一個結構作為輸入參數。 結構在頭文件中定義如下:
struct MyStruct
{
int siOrder;
char aaszNames[6][25];
int siId[6];
int siTones[6];
};
我試圖將托管結構聲明如下:
[StructLayoutAttribute(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct MyStruct {
public int siOrder;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst=150)]
public string aaszNames;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=6, ArraySubType=UnmanagedType.I4)]
public int[] siId;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=6, ArraySubType=UnmanagedType.I4)]
public int[] siTones;
}
但沒有任何成功。 我猜測編組失敗了,因為aaszNames實際上是一個由六個25長的空終止字符串組成的數組。 我嘗試將aaszNames聲明為
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=150)]
public char[] aaszNames;
必要時用空值填充數組。 但是,再一次,沒有。
有什么我想念的嗎? 我錯了什么? 編組這個2-D char數組的最佳方法是什么?
請給我任何提示。
嘗試使用多個C#結構:
[StructLayoutAttribute(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct MyStruct_Name
{
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 25)]
public string name;
}
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MyStruct
{
public int siOrder;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6)]
public MyStruct_Name aaszNames;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I4)]
public int[] siId;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I4)]
public int[] siTones;
}
這就是我傳遞C風格字符串數組的方式。
別忘了創建aaszNames的內容! marshaller討厭空引用。
MyStruct foo = new MyStruct();
for (int i = 0; i < 6; i++)
{
foo.aaszNames[i] = new MyStruct_Name();
foo.aaszNames[i].name = "";
}
祝好運!
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=150)]
public char[] aaszNames;
編組類型看起來很好。 可能在函數調用中發出問題,或者內存分配錯誤/
我會寫一個小的c程序來檢查C結構的字節大小。
然后我會按照另一個建議來逐字段提取數據。
從C的角度來看,/ 0被視為包含在6個字節中的正常字符,而C#將使用長度為5並且隱藏/ 0。
char aaszNames[6][25];
C ++類型的char是8位〜
但C#Type的字符是Unicode,(16位)!
所以C ++的char類型< - > C#類型的字節
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.