封送指向字符串数组 [英] Marshaling pointer to an array of strings
问题描述
我有一些麻烦,封送一个指向字符串数组。它看起来无害的是这样的:
I am having some trouble marshaling a pointer to an array of strings. It looks harmless like this:
typedef struct
{
char* listOfStrings[100];
} UnmanagedStruct;
这实际上是嵌入另一个这样的结构里面:
This is actually embedded inside another structure like this:
typedef struct
{
UnmanagedStruct umgdStruct;
} Outerstruct;
非托管代码调用返回到托管代码,返回Outerstruct作为一个IntPtr内存分配和填充值。
Unmanaged code calls back into managed code and returns Outerstruct as an IntPtr with memory allocated and values filled in.
[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并提取字符串一个接一个。
If I change listOfStrings to simply be an IntPtr then Marshal.PtrToStructure works but now I am unable to rip into listOfStrings and extract the strings one by one.
推荐答案
行..我好像它得到工作。应该封送IntPtr的[]
OK.. I seem to have got it to work. It should be marshaled as IntPtr[]
这似乎工作:
[StructLayout(LayoutKind.Sequential)]
public struct UnmanagedStruct
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=100)]
public IntPtr[] listOfStrings;
}
for (int i = 0; i < 100; ++i)
{
if (listOfstrings[i] != IntPtr.Zero)
Console.WriteLine(Marshal.PtrToStringAnsi(listOfStrings[i]));
}
这篇关于封送指向字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!