指向C ++ / CLI中托管阵列的指针

时间:2022-06-15 05:31:08

Alright, I know how you normally would declare a pointer:

好吧,我知道你通常会如何声明一个指针:

void SomeFunction(array<float> ^managedArray)
{
  pin_ptr<float> managedArrayPtr = &managedArray[0];
}

This works fine except when managedArray contains no elements. In that case, it throws an IndexOutOfRangeException.

这工作正常,除非managedArray不包含任何元素。在这种情况下,它会抛出IndexOutOfRangeException。

In C# you can do this:

在C#中你可以这样做:

void SomeFunction(float[] managedArray)
{
  fixed (float* managedArrayPtr = managedArray)
  {
  }
}

Which does no memory access and works even if managedArray is empty. Do I really have to check for the number of elements everywhere I use pointers to managed arrays or does C++/CLI have a way to do it like C#? It should be using the 'lea' instruction in ASM which does no memory access.

即使managedArray为空,也没有内存访问权限。我是否真的必须检查每个地方使用指向托管数组的指针的元素数量,或者C ++ / CLI是否有办法像C#那样做?它应该使用ASM中的'lea'指令,它不进行内存访问。

Any help is greatly appreciated!

任何帮助是极大的赞赏!

2 个解决方案

#1


3  

There isn't much point in trying to read from the array when it is empty. Just check for that:

尝试从数组中读取时没有太多意义。只需检查一下:

void SomeFunction(array<float> ^managedArray)
{
    if (managedArray->Length > 0) {
        pin_ptr<float> managedArrayPtr = managedArray;
        //etc...
    }
}

#2


1  

Good question. Unfortunately I am not that familiar with C++/CLI. I do know that you can do the pinning manually using the GCHandle struct and will work on empty arrays. It is not as elegant as using pin_ptr though.

好问题。不幸的是,我对C ++ / CLI并不熟悉。我知道你可以使用GCHandle结构手动执行固定,并且可以在空数组上工作。它并不像使用pin_ptr那样优雅。

void SomeFunction(array<float> ^managedArray) 
{ 
 GCHandle handle = GCHandle::Alloc(managedArray, GCHandleType::Pinned);
 try 
 {
  float* ptr = (float*)(void*)handle.AddrOfPinnedObject();
 }
 finally
 {
  handle.Free();
 }
} 

#1


3  

There isn't much point in trying to read from the array when it is empty. Just check for that:

尝试从数组中读取时没有太多意义。只需检查一下:

void SomeFunction(array<float> ^managedArray)
{
    if (managedArray->Length > 0) {
        pin_ptr<float> managedArrayPtr = managedArray;
        //etc...
    }
}

#2


1  

Good question. Unfortunately I am not that familiar with C++/CLI. I do know that you can do the pinning manually using the GCHandle struct and will work on empty arrays. It is not as elegant as using pin_ptr though.

好问题。不幸的是,我对C ++ / CLI并不熟悉。我知道你可以使用GCHandle结构手动执行固定,并且可以在空数组上工作。它并不像使用pin_ptr那样优雅。

void SomeFunction(array<float> ^managedArray) 
{ 
 GCHandle handle = GCHandle::Alloc(managedArray, GCHandleType::Pinned);
 try 
 {
  float* ptr = (float*)(void*)handle.AddrOfPinnedObject();
 }
 finally
 {
  handle.Free();
 }
}