[英]Marshaling a pointer to an array of types (managed C# -> unmanaged C++)
I am having some trouble settling on a way to represent a structure that contains a pointer to an array of shorts in my managed code. 我在解决一种表示结构的方法上遇到了麻烦,该结构包含一个指向托管代码中短裤数组的指针。 The struct looks like this:
该结构如下所示:
typedef struct
{
short size;
unsigned short** shortValues;
} UnmanagedStruct;
memory for ' shortValues
' is allocated inside unmanaged code -- therefore even though that field is simply a pointer to an array of short values, an additional level of indirection was added so that allocated memory is seen by the caller (managed code) too. “
shortValues
”的内存是在非托管代码中分配的-因此,即使该字段只是指向短值数组的指针,也添加了附加级别的间接寻址,以便调用者(托管代码)也可以看到分配的内存。 The ' size
' field represents the number of elements in the array. “
size
”字段表示数组中元素的数量。 How do I represent this in managed code? 我该如何在托管代码中表示呢?
I thought I'd pass it in just an IntPtr
, then I couldn't figure out how to access the values once the unmanaged call returns. 我以为只在
IntPtr
传递了它,所以一旦非托管调用返回,我想不通如何访问这些值。
Is unsafe code ok? 不安全的代码可以吗?
public unsafe struct UnmanagedStruct
{
public short size;
public ushort** shortValues;
}
[DllImport("example.dll")]
public static extern void GetUnmanagedStruct(out UnmanagedStruct s);
If you have a pointer to an array of ushort
s: 如果您有一个指向
ushort
数组的指针:
public static unsafe void WriteValues()
{
UnmanagedStruct s;
GetUnmanagedStruct(out s);
for (var i = 0; i < s.size; i++)
{
ushort x = (*s.shortValues)[i];
Console.WriteLine(x);
}
}
If you have an array of null-terminated arrays of ushort
s: 如果您有
ushort
s的以null结尾的数组:
public static unsafe void WriteValues()
{
UnmanagedStruct s;
GetUnmanagedStruct(out s);
for (var i = 0; i < s.size; i++)
{
for (ushort* p = s.shortValues[i]; p != null; p++)
{
ushort x = *p;
Console.WriteLine(x);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.