如何将字符串数组复制到非托管字符双指针? [英] How can I copy a array of strings into an unmanaged char double pointer?
问题描述
我在C结构中有一个char**
,它在C代码中分配为 Nx128 矩阵.在C#中,我有一个字符串数组,我想将此数组复制到char double指针,而无需重新分配任何内容.我试过了:
I have a char**
in a C struct which is allocated in the C code as a Nx128 matrix. In C# I have an array of strings and I want to copy this array to the char double pointer, without reallocating anything. I tried this:
public void StringArrayToPtr(IntPtr ptr, string[] array)
{
for (int i = 0; i < array.Length; i++)
{
char[] chars = (array[i] + '\0').ToCharArray();
Marshal.Copy(chars, 0, IntPtr.Add(ptr, 128*i), chars.Length);
}
}
但这不起作用. 有人知道如何执行这种复制吗?
更新:
这是我的char** names
在C代码中分配给3个项目的方式:names = (char **) MallocArray2D (3, 128, sizeof ( char ));
Here is how my char** names
is allocated in the C code for 3 items: names = (char **) MallocArray2D (3, 128, sizeof ( char ));
这是MallocArray2D
方法的详细信息:
void ** MallocArray2D (
int n1,
int n2,
int size_elem )
{
void ** p2;
void * p1;
size_t i;
p1 = (void *) malloc (size_elem * n1 * n2);
p2 = (void **) malloc (n1 * sizeof ( void * ));
for ( i = 0 ; i < n1 ; i++ )
{
p2[i] = (char *) p1 + size_elem * n2 * i;
}
return p2;
}
此MallocArray2D
方法被调用到MallocImage
中,该方法在我的C#代码中公开.
This MallocArray2D
method is called into a MallocImage
which is exposed in my C# code.
这是C代码中MallocImage
方法有趣的部分:
Here is the MallocImage
method interesting part in C code:
int MallocImage (
IMAGE * image,
int nxyz,
int nvar )
{
//... Allocating others objects
image->names = (char **) MPDSMallocArray2D ( nvar, 128, sizeof ( char ));
}
现在我的C#公开了MallocImage
方法:
Now my C# exposed MallocImage
method:
[DllImport(DLL_PATH, CallingConvention = CallingConvention.Cdecl)]
public static extern int MallocImage([In, Out]Image image, int nXYZ, int nVar);
// My Image class
[StructLayout(LayoutKind.Sequential)]
class Image {
private IntPtr names;
public string[] Names {
set {ArrayOfStringToPtr(names, value);}
}
// Constructor
public Image(int nVar, int nXYZ) {
MallocImage(this, nXYZ, nVar);
}
}
// Somewhere else in my code
image.Names = new string[] {"porosity", "duplicity", "facies"];
推荐答案
A System.Char
is a unicode 16 bits character [MSDN]. You probably work with ASCII string.
这里的指针算法似乎是错误的,因为您正在使用指向三个指针的数组的指针,您可能需要使用Marshal.ReadIntPtr(ptr, i * IntPtr.Size)
获取字符串的地址,因此代码将是:
The pointer arithmetic seems wrong here, since you are working with a pointer who points to an array of three pointers you probably need to get the address of the string using : Marshal.ReadIntPtr(ptr, i * IntPtr.Size)
thus the resulting code will be :
public static void StringArrayToPtr(IntPtr ptr, string[] array)
{
for (int i = 0; i < array.Length; i++)
{
byte[] chars = System.Text.Encoding.ASCII.GetBytes(array[i] + '\0');
Marshal.Copy(chars, 0, Marshal.ReadIntPtr(ptr, i * IntPtr.Size), chars.Length);
}
}
这篇关于如何将字符串数组复制到非托管字符双指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!