如何在List 中获取数组的IntPtr?(How to get IntPtr of the array within List?)

编程入门 行业动态 更新时间:2024-10-25 11:21:25
如何在List 中获取数组的IntPtr?(How to get IntPtr of the array within List?)

我正在使用一个库,它有一个函数SendBuffer(int size, IntPtr pointer)和IntPtr作为参数。

var list = new List<float>{3, 2, 1}; IntPtr ptr = list.getPointerToInternalArray(); SendBuffer(ptr, list.Count);

如何从存储在List<T> (和/或T[] )中的数组中获取IntPtr ?

I'm using a library which has a function SendBuffer(int size, IntPtr pointer) with IntPtr as a parameter.

var list = new List<float>{3, 2, 1}; IntPtr ptr = list.getPointerToInternalArray(); SendBuffer(ptr, list.Count);

How to get IntPtr from the array stored in List<T> (and/or T[])?

最满意答案

数组每帧发送一次,它很大

在这种情况下,可能需要访问List使用的内部后备阵列。 面对未来的.NET版本,这是一个破解和脆弱。 那就是说.NET使用了一个非常高的兼容性栏,它们可能不会改变这种核心类型的字段名称。 此外,出于性能原因,我们几乎可以保证List将始终为其项目使用单个后备阵列。 因此,虽然这是一种高风险技术,但在此可能是必要的。

或者,更好的是,编写您自己控制的List,并从中获取数组。 (因为你似乎关注perf我不知道你为什么要使用List<float>因为访问项目比普通数组慢。)

获取数组,然后使用fixed(float* ptr = array) SendBuffer(ptr, length)来固定它并传递它而不复制内存。

这里不需要使用笨拙且缓慢的GCHandle类型。 使用fixed使用IL功能可以实现超快速。 应该接近零成本。

The array is sent every frame and it's big

In that case it might be warranted to access the internal backing array that List uses. This is a hack and brittle in the face of future .NET versions. That said .NET uses a very high compatibility bar and they probably would not change a field name in such a core type. Also, for performance reasons it is pretty much guaranteed that List will always use a single backing array for its items. So although this is a high risk technique it might be warranted here.

Or, better yet, write your own List that you control and that you can get the array from. (Since you seem to be concerned with perf I wonder why you are using List<float> anyway because accessing items is slower compared to a normal array.)

Get the array, then use fixed(float* ptr = array) SendBuffer(ptr, length) to pin it and pass it without copying memory.

There is not need to use the awkward and slow GCHandle type here. Pinning using fixed uses an IL feature to make this super fast. Should be near zero cost.

更多推荐

本文发布于:2023-07-30 06:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336731.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   如何在   array   List   IntPtr

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!