[英]How do I marshal a struct that contains a variable-sized array to C#?
如何封送这种C ++类型?
ABS_DATA结构用于将任意长的数据块与长度信息相关联。 Data
数组的声明长度为1,但实际长度由Length
成员给定。
typedef struct abs_data {
ABS_DWORD Length;
ABS_BYTE Data[ABS_VARLEN];
} ABS_DATA;
我尝试了以下代码,但无法正常工作。 数据变量始终为空,我确定其中有数据。
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
public struct abs_data
{
/// ABS_DWORD->unsigned int
public uint Length;
/// ABS_BYTE[1]
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 1)]
public string Data;
}
老问题了,但是我最近不得不自己做,所有现有的答案都很差,所以...
在结构中封送可变长度数组的最佳解决方案是使用自定义封送程序 。 这使您可以控制运行时用来在托管数据和非托管数据之间转换的代码。 不幸的是,自定义封送处理的文献记录很少,并且有一些奇怪的限制。 我将快速介绍这些内容,然后再解决问题。
令人讨厌的是,您不能在结构或类的数组元素上使用自定义封送处理。 没有记录或逻辑上的限制说明,编译器也不会抱怨,但是您会在运行时遇到异常。 另外,有一个自定义封送程序必须实现的函数int GetNativeDataSize()
,这显然不可能准确实现(它不会向您传递对象的实例来询问其大小,因此您只能关闭该类型,当然是可变大小的!)幸运的是,此功能无关紧要。 我从来没有见过它被调用过,并且即使它返回假值(一个MSDN示例中它返回-1),自定义封送程序也能正常工作。
首先,这是我认为您的本机原型可能是什么样子(我在这里使用P / Invoke,但它也适用于COM):
// Unmanaged C/C++ code prototype (guess)
//void DoThing (ABS_DATA *pData);
// Guess at your managed call with the "marshal one-byte ByValArray" version
//[DllImport("libname.dll")] public extern void DoThing (ref abs_data pData);
这是您可能如何使用自定义封送处理程序的天真的版本(它确实应该起作用)。 我会稍等一下...
[StructLayout(LayoutKind.Sequential)]
public struct abs_data
{
// Don't need the length as a separate filed; managed arrays know it.
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(ArrayMarshaler<byte>))]
public byte[] Data;
}
// Now you can just pass the struct but it takes arbitrary sizes!
[DllImport("libname.dll")] public extern void DoThing (ref abs_data pData);
不幸的是,在运行时,您显然无法将数组中的数组编组为SafeArray
或ByValArray
之外的任何其他东西。 SafeArrays被计算在内,但看起来却与您在这里寻找的(极其常见)的格式完全不同。 这样就行不通了。 当然,ByValArray要求在编译时知道该长度,因此(在遇到问题时)也不起作用。 但是,奇怪的是,您可以在数组参数上使用自定义封送处理,这很烦人,因为您必须将MarshalAsAttribute
放在使用此类型的每个参数上,而不是仅将其放在一个字段上并使其应用到所有使用包含该类型的类型的地方字段,但c'est la vie。 看起来像这样:
[StructLayout(LayoutKind.Sequential)]
public struct abs_data
{
// Don't need the length as a separate filed; managed arrays know it.
// This isn't an array anymore; we pass an array of this instead.
public byte Data;
}
// Now you pass an arbitrary-sized array of the struct
[DllImport("libname.dll")] public extern void DoThing (
// Have to put this huge stupid attribute on every parameter of this type
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(ArrayMarshaler<abs_data>))]
// Don't need to use "ref" anymore; arrays are ref types and pass as pointer-to
abs_data[] pData);
在该示例中,我保留了abs_data
类型,以防您要对其进行特殊操作(构造函数,静态函数,属性,继承等)。 如果数组元素由复杂类型组成,则可以修改该结构以表示该复杂类型。 但是,在这种情况下, abs_data
基本上只是一个重命名的字节-它甚至没有“包装”该字节。 就本机代码而言,它更像是typedef-因此您可以传递一个字节数组并完全跳过该结构:
// Actually, you can just pass an arbitrary-length byte array!
[DllImport("libname.dll")] public extern void DoThing (
// Have to put this huge stupid attribute on every parameter of this type
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(ArrayMarshaler<byte>))]
byte[] pData);
OK,现在您可以看到如何声明数组元素类型(如果需要),以及如何将数组传递给非托管函数。 但是,我们仍然需要该自定义封送程序。 您应该阅读“ 实现ICustomMarshaler接口 ”,但是我将在此用内联注释对此进行介绍。 请注意,我使用一些速记约定(例如Marshal.SizeOf<T>()
),它们需要.NET 4.5.1或更高版本。
// The class that does the marshaling. Making it generic is not required, but
// will make it easier to use the same custom marshaler for multiple array types.
public class ArrayMarshaler<T> : ICustomMarshaler
{
// All custom marshalers require a static factory method with this signature.
public static ICustomMarshaler GetInstance (String cookie)
{
return new ArrayMarshaler<T>();
}
// This is the function that builds the managed type - in this case, the managed
// array - from a pointer. You can just return null here if only sending the
// array as an in-parameter.
public Object MarshalNativeToManaged (IntPtr pNativeData)
{
// First, sanity check...
if (IntPtr.Zero == pNativeData) return null;
// Start by reading the size of the array ("Length" from your ABS_DATA struct)
int length = Marshal.ReadInt32(pNativeData);
// Create the managed array that will be returned
T[] array = new T[length];
// For efficiency, only compute the element size once
int elSiz = Marshal.SizeOf<T>();
// Populate the array
for (int i = 0; i < length; i++)
{
array[i] = Marshal.PtrToStructure<T>(pNativeData + sizeof(int) + (elSiz * i));
}
// Alternate method, for arrays of primitive types only:
// Marshal.Copy(pNativeData + sizeof(int), array, 0, length);
return array;
}
// This is the function that marshals your managed array to unmanaged memory.
// If you only ever marshal the array out, not in, you can return IntPtr.Zero
public IntPtr MarshalManagedToNative (Object ManagedObject)
{
if (null == ManagedObject) return IntPtr.Zero;
T[] array = (T[])ManagedObj;
int elSiz = Marshal.SizeOf<T>();
// Get the total size of unmanaged memory that is needed (length + elements)
int size = sizeof(int) + (elSiz * array.Length);
// Allocate unmanaged space. For COM, use Marshal.AllocCoTaskMem instead.
IntPtr ptr = Marshal.AllocHGlobal(size);
// Write the "Length" field first
Marshal.WriteInt32(ptr, array.Length);
// Write the array data
for (int i = 0; i < array.Length; i++)
{ // Newly-allocated space has no existing object, so the last param is false
Marshal.StructureToPtr<T>(array[i], ptr + sizeof(int) + (elSiz * i), false);
}
// If you're only using arrays of primitive types, you could use this instead:
//Marshal.Copy(array, 0, ptr + sizeof(int), array.Length);
return ptr;
}
// This function is called after completing the call that required marshaling to
// unmanaged memory. You should use it to free any unmanaged memory you allocated.
// If you never consume unmanaged memory or other resources, do nothing here.
public void CleanUpNativeData (IntPtr pNativeData)
{
// Free the unmanaged memory. Use Marshal.FreeCoTaskMem if using COM.
Marshal.FreeHGlobal(pNativeData);
}
// If, after marshaling from unmanaged to managed, you have anything that needs
// to be taken care of when you're done with the object, put it here. Garbage
// collection will free the managed object, so I've left this function empty.
public void CleanUpManagedData (Object ManagedObj)
{ }
// This function is a lie. It looks like it should be impossible to get the right
// value - the whole problem is that the size of each array is variable!
// - but in practice the runtime doesn't rely on this and may not even call it.
// The MSDN example returns -1; I'll try to be a little more realistic.
public int GetNativeDataSize ()
{
return sizeof(int) + Marshal.SizeOf<T>();
}
}
哇,好长! 好吧,那里有。 我希望人们看到这一点,因为那里有很多错误的答案和误解...
这是不可能的包含可变长度数组编组结构(但它是可能的编组可变长度数组作为函数参数)。 您将必须手动读取数据:
IntPtr nativeData = ... ;
var length = Marshal.ReadUInt32 (nativeData) ;
var bytes = new byte[length] ;
Marshal.Copy (new IntPtr ((long)nativeData + 4), bytes, 0, length) ;
如果要保存的数据不是字符串,则不必将其存储在字符串中。 除非原始数据类型为char*
否则我通常不编组字符串。 否则, byte[]
应该起作用。
尝试:
[MarshalAs(UnmanagedType.ByValArray, SizeConst=[whatever your size is]]
byte[] Data;
如果以后需要将其转换为字符串,请使用:
System.Text.Encoding.UTF8.GetString(your byte array here).
显然,尽管UTF-8通常就足够了,但您仍需要根据需要更改编码。
我现在看到了问题,您必须封送一个VARIABLE长度数组。 MarshalAs不允许这样做,并且必须通过引用发送数组。
如果数组长度可变,则您的byte[]
必须为IntPtr,因此您可以使用,
IntPtr Data;
代替
[MarshalAs(UnmanagedType.ByValArray, SizeConst=[whatever your size is]]
byte[] Data;
然后,您可以使用Marshal类访问基础数据。
就像是:
uint length = yourABSObject.Length;
byte[] buffer = new byte[length];
Marshal.Copy(buffer, 0, yourABSObject.Data, length);
您可能需要在完成操作后清理内存以避免泄漏,尽管我怀疑当yourABSObject超出范围时GC会清理内存。 无论如何,这是清理代码:
Marshal.FreeHGlobal(yourABSObject.Data);
您试图byte[ABS_VARLEN]
一个byte[ABS_VARLEN]
东西,好像它是一个长度为1的string
。您需要弄清楚ABS_VARLEN常量是什么,并将数组封送为:
[MarshalAs(UnmanagedType.LPArray, SizeConst = 1024)]
public byte[] Data;
(1024中有一个占位符;请填写ASB_VARLEN的实际值。)
我认为,固定数组并获取其地址更简单,更有效。
假设您需要将abs_data
传递给myNativeFunction(abs_data*)
:
public struct abs_data
{
public uint Length;
public IntPtr Data;
}
[DllImport("myDll.dll")]
static extern void myNativeFunction(ref abs_data data);
void CallNativeFunc(byte[] data)
{
GCHandle pin = GCHandle.Alloc(data, GCHandleType.Pinned);
abs_data tmp;
tmp.Length = data.Length;
tmp.Data = pin.AddrOfPinnedObject();
myNativeFunction(ref tmp);
pin.Free();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.