我在編組指向字符串數組的指針時遇到了一些麻煩。它看起來無害的像這樣:封裝指向字符串數組的指針
typedef struct
{
char* listOfStrings[100];
} UnmanagedStruct;
這實際上是嵌入到另一個結構裏面是這樣的:
typedef struct
{
UnmanagedStruct umgdStruct;
} Outerstruct;
非託管代碼回調到託管代碼,返回Outerstruct作爲一個IntPtr與分配的內存和值填充。
管理世界:
[StructLayout(LayoutKind.Sequential)]
public struct UnmanagedStruct
{
[MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr, SizeConst=100)]
public string[] listOfStrings;
}
[StructLayout(LayoutKind.Sequential)]
public struct Outerstruct
{
public UnmanagedStruct ums;
}
public void CallbackFromUnmanagedLayer(IntPtr outerStruct)
{
Outerstruct os = Marshal.PtrToStructure(outerStruct, typeof(Outerstruct));
// The above line FAILS! it throws an exception complaining it cannot marshal listOfStrings field in the inner struct and that its managed representation is incorrect!
}
如果我將listOfStrings更改爲IntPtr,Marshal.PtrToStructure就可以工作,但現在我無法翻譯成listOfStrings並逐個提取字符串。
ByValArray ==就地數組,LPArray ==指向數組的指針。儘管SizeConst仍然應該使用LPArray,所以編組時的錯誤有點奇怪。 – 2009-08-24 18:13:30
噢,如果你有public string [] listOfStrings,它的ByValArray會讓我認爲有所不同。 – 2009-08-24 18:14:18