必要的pin_ptr上C ++ CLR值类型,为什么? [英] Necessary to pin_ptr on C++ CLR Value types, why?

查看:195
本文介绍了必要的pin_ptr上C ++ CLR值类型,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于.NET Value类型(托管C ++结构体)存储在Stack上,为什么需要pin_ptr来传递指向非托管函数的指针呢?

Since .NET Value types (managed C++ structs) are stored on the Stack why is it (or, alternatively is it actually) necessary to pin_ptr them in order to pass a pointer to an unmanaged function?

例如。 BYTE b [100];

Eg. BYTE b[100];

如果我将& b传递到非托管函数而不先锁定它,

If I pass &b to an unmanaged function without first pinning it, may the stack become corrupted?

CLR堆栈是否会以与GC堆相同的方式进行更改?我导致相信,CLR堆栈使用不寻常的优化,如使用处理器寄存器,这使得它不适合用作非管理功能的缓冲区。

Is the CLR stack subject to change in the same way as the GC Heap? I am led to believe that the CLR Stack uses unusual optimizations such as using processor registers which makes it unsuitable for use as buffer to unmanaged functions. The rules regarding pinning value types on the stack seem to be unclear.

我注意到,当以这种方式将缓冲区数组发送到内核NTDLL函数时,这似乎是一些损坏NtfsControlFile。固定值类型解决了问题。

I have noticed what seems to be some corruption when sending buffer arrays in this way to the kernel NTDLL function NtfsControlFile. Pinning the value type solves the problem. But never to an API call.

因此,根本不安全的是,任何指针的任何值类型的堆栈上的任何非托管函数,没有先固定他们?

Is it not therefore, fundamentally unsafe to pass any pointers to any value types on the stack to any unmanaged functions, without first pinning them?

推荐答案

您确定 BYTE b [100]; 在本机栈上,因此不受托管堆移动等等。但是我相信你的问题是一个简单的C ++错误。

You are correct that BYTE b[100]; is created on the native stack and therefore is not subject to managed heap moving, etc. However I believe your problem is a simple C++ mistake.

你说,


如果我将& b传递给非托管函数
,而不先将其固定,那么
堆栈是否会损坏?

If I pass &b to an unmanaged function without first pinning it, may the stack become corrupted?

您不应该在数组名称(b)上使用运算符地址(&),因为数组名称本身已经是地址的数组的开始。使用& b 将不起作用,并且结果行为将取决于多个因素(例如,编译器及其设置)。

You should not be using the address-of operator (&) on the array name (b) since the array name by itself is already the address of the start of the array. Using &b will not work, and the resulting behavior will depend upon multiple factors (e.g., the compiler and its settings).

简单地说,你应该只是传递数组名(b),而不是在调用函数时使用数组名(& b)上的操作符的地址。

Simply stated, you should just be passing the array name (b) instead of using the address-of operator on the array name (&b) when calling the function.

顺便说一下,我相信你混淆了问题,通过询问是否可以传递一个托管值类型的堆栈到一个本机函数,而不先锁定它,因为你给的例子是传递一个非托管,基于堆栈的本机数组类型,这与托管值类型无关。

By the way, I believe you are mixing up issues by asking whether one may pass a managed value type on the stack to a native function without first pinning it, since the example you give is that of passing an unmanaged, stack-based native array type, which has nothing to do with managed value types.

这篇关于必要的pin_ptr上C ++ CLR值类型,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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