指向 C++/CLI 中托管数组的指针
好吧,我知道你通常会如何声明一个指针:
void SomeFunction(array<float> ^managedArray)
{
pin_ptr<float> managedArrayPtr = &managedArray[0];
}
这工作得很好,除非 ManagedArray 不包含任何元素。在这种情况下,它会抛出 IndexOutOfRangeException。
在 C# 中,您可以这样做:
void SomeFunction(float[] managedArray)
{
fixed (float* managedArrayPtr = managedArray)
{
}
}
它不进行内存访问,即使 ManagedArray 为空也能工作。 我是否真的必须在所有使用托管数组指针的地方检查元素的数量,或者 C++/CLI 是否有办法像 C# 那样执行此操作? 它应该使用 ASM 中的“lea”指令,该指令不进行内存访问。
非常感谢任何帮助!
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.
In C# you can do this:
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.
Any help is greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当数组为空时尝试读取它没有多大意义。只需检查一下:
There isn't much point in trying to read from the array when it is empty. Just check for that:
好问题。不幸的是我对 C++/CLI 不太熟悉。我确实知道您可以使用 GCHandle 结构手动进行固定,并且可以处理空数组。但它并不像使用
pin_ptr
那么优雅。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 usingpin_ptr
though.