将字符串数组从 ANSI C 编组到 C# 中的字符串 []
Marshalling string array from ANSI C to string[] in C#
我正在寻找将字符串数组从 ANSI C 编组到 C# 中的字符串 [] 的解决方案。
在 ANSI C 中看起来像:
const char *cities[] = {"Moscow", "New York", "London"};
在 C# 中,我有一个 System.IntPtr IntPtrCities,我想将其转换为字符串列表:
string[] citiesList
我还需要将此解决方案反转...从 C# 中的 string[] citiesList 到 System.IntPtr IntPtrCities 到 ANSI C char ** cities.
我试过 Marshal.PtrToStringAnsi 但它只适用于一个字符串,而且我不知道 ANSI C 层的字符串列表大小。
You cannot marshal an array directly from native to managed code without knowing the size of the array.
谢谢。这就是重要信息!
在找到这个:https://limbioliong.wordpress.com/2011/08/14/returning-an-array-of-strings-from-c-to-c-part-1/
// This method transforms an array of unmanaged character pointers (pointed to by pUnmanagedStringArray)
// into an array of managed strings.
//
// This method also destroys each unmanaged character pointers and will also destroy the array itself.
static void MarshalUnmananagedStrArray2ManagedStrArray(IntPtr pUnmanagedStringArray, int StringCount, out string[] ManagedStringArray)
{
IntPtr[] pIntPtrArray = new IntPtr[StringCount];
ManagedStringArray = new string[StringCount];
Marshal.Copy(pUnmanagedStringArray, pIntPtrArray, 0, StringCount);
for (int i = 0; i < StringCount; i++)
{
ManagedStringArray[i] = Marshal.PtrToStringAnsi(pIntPtrArray[i]);
Marshal.FreeCoTaskMem(pIntPtrArray[i]);
}
Marshal.FreeCoTaskMem(pUnmanagedStringArray);
}
我正在寻找将字符串数组从 ANSI C 编组到 C# 中的字符串 [] 的解决方案。
在 ANSI C 中看起来像:
const char *cities[] = {"Moscow", "New York", "London"};
在 C# 中,我有一个 System.IntPtr IntPtrCities,我想将其转换为字符串列表:
string[] citiesList
我还需要将此解决方案反转...从 C# 中的 string[] citiesList 到 System.IntPtr IntPtrCities 到 ANSI C char ** cities.
我试过 Marshal.PtrToStringAnsi 但它只适用于一个字符串,而且我不知道 ANSI C 层的字符串列表大小。
You cannot marshal an array directly from native to managed code without knowing the size of the array.
谢谢。这就是重要信息!
在找到这个:https://limbioliong.wordpress.com/2011/08/14/returning-an-array-of-strings-from-c-to-c-part-1/
// This method transforms an array of unmanaged character pointers (pointed to by pUnmanagedStringArray)
// into an array of managed strings.
//
// This method also destroys each unmanaged character pointers and will also destroy the array itself.
static void MarshalUnmananagedStrArray2ManagedStrArray(IntPtr pUnmanagedStringArray, int StringCount, out string[] ManagedStringArray)
{
IntPtr[] pIntPtrArray = new IntPtr[StringCount];
ManagedStringArray = new string[StringCount];
Marshal.Copy(pUnmanagedStringArray, pIntPtrArray, 0, StringCount);
for (int i = 0; i < StringCount; i++)
{
ManagedStringArray[i] = Marshal.PtrToStringAnsi(pIntPtrArray[i]);
Marshal.FreeCoTaskMem(pIntPtrArray[i]);
}
Marshal.FreeCoTaskMem(pUnmanagedStringArray);
}