.NET对象的钢钉阵钢钉、对象、NET

2023-09-04 02:45:47 作者:还没握紧你的手你就放手了

我想针.NET对象(包括对象)的数组,以便让本机的功能做一些处理上的对象。据我了解,GCHandle.Alloc()不允许我这样做,因为这样的一个数组包含引用(和对象可能还包括参考)不是blittable。

I would like to pin an array of .NET objects (including the objects) in order to allow a native function to do some processing on the objects. As far as I understood, GCHandle.Alloc() does not allow me to do this, because such an array contains references (and the objects might also contain references) which are not blittable.

是否有任何其他选项,以实现这一目标?我会好起来的与需要单非常黑客-Y建议或1。

Is there any other option to achieve this? I would be okay with very hack-y suggestions or ones that require Mono.

推荐答案

在.NET数组重新$ P $。因此,这意味着,在存储器中,元素0后,元件1会来的后直接的所述previous元件,等等。

Arrays in .NET are represented in contiguous memory. So that means that in memory, after element 0, element 1 will come directly after the previous element, and so on.

如果你用针 GCHandle.Alloc ,那么这意味着的全部的元素列表是驻留在内存中,以及,你可以处理在非托管code。

If you pin the array with GCHandle.Alloc, then that means the entire list of elements is pinned in memory as well, and you can process that in unmanaged code.

然而,正如你提到的,它才有意义,如果该类型是blittable类型(从技术上讲,这是不正确的,这是如果类型能够被封送到非托管code,虽然有很多重叠这里blittable主要类型和东西之间的的P / Invoke / COM互操作层自动处理)。

However, as you've mentioned, it only makes sense if the type is a blittable type (technically, this is not true, it's if the type is able to be marshaled to unmanaged code, although there's a lot of overlap here between the blittable primary types and stuff that the P/Invoke/COM Interop layers handle automatically).

所以,如果你有值类型的数组,可以调用 GCHandle.Alloc ,它将针阵列为您服务。然而,P /调用层的已的做到这一点给你,所以你不应该与此有关。

So if you have an array of value types, you can call GCHandle.Alloc and it will pin the array for you. However, the P/Invoke layer already does this for you, so you shouldn't be concerned with this.

如果您的数组已满引用,然后将其编组到unamanged code就没有意义了,反正;即使你每针参考,非托管的code不知道做什么用的内存引用,作为类型系统不支持.NET类型的引用指向内存中。

If your array is full of references, then marshalling it to unamanged code doesn't make sense anyways; even if you pin every reference, the unmanaged code wouldn't know what to do with that reference in memory, as the type system doesn't support the .NET type that the reference is pointing to in memory.

如果这个类在.NET是一个真正的天然结构的封装/ .NET重新presentation,那么你最好创建一个结构在.NET中的一个阵列,所有的数据复制到它,然后将它发送给你的本地code。

If the class in .NET is really a wrapper/.NET representation of a native structure, then you're better off creating an array of that structure in .NET, copying all the data into it, and then sending it to your native code.

或者,你可以写你的类在C ++ / CLI,方便.NET成员在本地code中的访问。

Or, you could write your class in C++/cli to facilitate the access of the .NET members in native code.

 
精彩推荐
图片推荐