如何获得一个指向数组实例内存的指针? [英] How to get a pointer to memory of Array instance?

查看:74
本文介绍了如何获得一个指向数组实例内存的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

网络上有很多示例如何获取指向 byte [] int [,] 的指针,即,当您确切知道数组的元素类型和等级时。但是如何获取通用 Array 的指针?

There are many examples over the net how to get pointer to byte[] or int[,], i.e. when you know exactly the element type and rank of the array. But how to get the pointer for generic Array?

这里的主要问题是我不知道排名靠前。我也不知道元素类型,但是我知道只能有原始数字类型,所以我可以输入一些额外的 if 来应对。

The main problem here is I don't know rank in the advance. I don't know element type too but I know there can be only primitive numeric type (in my case), so I could type few extra ifs to cope with it.

背景:我想提出此解决方案 https://stackoverflow.com / a / 52750659/6734314 更一般-在当前形式下,它仅与 double [,] 一起使用,因此给出了经典的rank + type:

Background: I would like to make this solution https://stackoverflow.com/a/52750659/6734314 more general -- in its current form it works only with double[,] so classic rank+type is given:

double[,] doubles =  {
     { 1, 2, 3, 4 },
     ...
};
fixed (double* p = doubles)
{
  ...

第一次尝试

从Olivier答案来看,所有错误都是我的。

From Olivier answer, all mistakes are mine.

Array data = new float[,] { { 4, 2 }, { 77, 3 } };
var reference = __makeref(data);
IntPtr pointer = **(IntPtr**)(&reference);

float* ptr = (float*)pointer.ToPointer();
{
  for (int i = 0; i < data.LongLength; ++i)
    Console.WriteLine(ptr[i]);
}


推荐答案

我想我找到了,如果发现太脆弱/可疑,请发表评论:

I think I found it, please comment if you found something too fragile/suspicious:

Array data = new float[,] { { 4, 2 }, { 77, 3 } };
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
try
{
  IntPtr address = handle.AddrOfPinnedObject();

  float* ptr = (float*)address.ToPointer();
  for (int i = 0; i < data.LongLength; ++i)
    Console.WriteLine(ptr[i]);
}
finally
{
  handle.Free();
}

这篇关于如何获得一个指向数组实例内存的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆