如何在不安全的 C# 代码中获取指向可变数量数组的指针
How can I get pointers to a variable number of arrays in unsafe C# code
如果我有一个 double[] 对象数组,其中数组的长度是预先知道的,那么我可以像这样设置一个指向 double[] 对象的指针数组:
int NumMatrices = 3;
double[][,] VectorOfMatrix = new double[NumMatrices][, ];
for (int i = 0; i < VectorOfMatrix.Length; i++) VectorOfMatrix[i] = new double[10, 10];
unsafe {
fixed (double* fpM0 = VectorOfMatrix[0], fpM1 = VectorOfMatrix[1], fpM2 = VectorOfMatrix[2]) {
double** ppMatrix = stackalloc double*[3];
ppMatrix[0] = fpM0;
ppMatrix[1] = fpM1;
ppMatrix[2] = fpM2;
...
}
}
但是如果事先不知道数组的长度,如何做等价的事情呢?
最终,你不能。它是“本地”上的一个标记,定义 从 JIT 的角度来看,某物是 fixed
,因此您 需要 每个 fixed
元素的“本地”,本地的数量是在编译时确定的,而不是运行时。
我 怀疑 当你需要那个人 inner-array 时,你会在 call-site 处需要一个本地范围的 fixed
- 但那是问题不大:fixed
是一种 非常便宜 的固定方式(它实际上只是堆栈上的参考副本,JIT 从上下文中知道它的意思是“固定” )
也就是说:我怀疑你也可以在这里使用跨度,绕过使用fixed
或指针的整个需要。
如果我有一个 double[] 对象数组,其中数组的长度是预先知道的,那么我可以像这样设置一个指向 double[] 对象的指针数组:
int NumMatrices = 3;
double[][,] VectorOfMatrix = new double[NumMatrices][, ];
for (int i = 0; i < VectorOfMatrix.Length; i++) VectorOfMatrix[i] = new double[10, 10];
unsafe {
fixed (double* fpM0 = VectorOfMatrix[0], fpM1 = VectorOfMatrix[1], fpM2 = VectorOfMatrix[2]) {
double** ppMatrix = stackalloc double*[3];
ppMatrix[0] = fpM0;
ppMatrix[1] = fpM1;
ppMatrix[2] = fpM2;
...
}
}
但是如果事先不知道数组的长度,如何做等价的事情呢?
最终,你不能。它是“本地”上的一个标记,定义 从 JIT 的角度来看,某物是 fixed
,因此您 需要 每个 fixed
元素的“本地”,本地的数量是在编译时确定的,而不是运行时。
我 怀疑 当你需要那个人 inner-array 时,你会在 call-site 处需要一个本地范围的 fixed
- 但那是问题不大:fixed
是一种 非常便宜 的固定方式(它实际上只是堆栈上的参考副本,JIT 从上下文中知道它的意思是“固定” )
也就是说:我怀疑你也可以在这里使用跨度,绕过使用fixed
或指针的整个需要。