为什么(错误地)使用 ref myarray[0] 传递数组可以工作,但只能在 32 位应用程序中使用? [英] Why does (incorrectly) using ref myarray[0] to pass in an array work, but only in 32bit Applications?

查看:23
本文介绍了为什么(错误地)使用 ref myarray[0] 传递数组可以工作,但只能在 32 位应用程序中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾在某个互操作(使用 DllImport)中做了一些愚蠢的事情,但它仍然可以在 32 位机器上运行.

I did something foolish in some interop (using DllImport) at one point, but it still worked on 32 bit machines.

在 64 位应用程序上有什么不同(以及为什么?)导致方法 1 的行为不同?

What is done differently (and why?) on a 64 bit application that causes Method 1 to behave differently ?

方法一(错误的方法):

Method 1 (wrong way):

ref byte param   //Signature of `DllImport`ed function
ref myarray[0]   //Parameter passed in when calling function

方法二(正确的方法):

Method 2 (right way):

byte[] param   //Signature of `DllImport`ed function  
myarray        //Parameter passed in when calling function  

无论哪种方式,导入函数最终看到的地址都应该是第一个数组元素的地址.由于数组将在内存中连续分配,因此我期望这两种方法是等效的.

Either way, the address the imported function eventually sees should be whatever the address of the first array element is. Since the array will be allocated contiguously in memory, my expectation was that these two methods would be equivalent.

应用程序是为 CPU 类型Any"编译的.在 32 位机器上,方法 1 和方法 2 都有效,并按预期运行.在 64 位机器上,只有方法 2 正常工作.使用方法 1,应用程序只能看到数组的第一个元素.数组的其余部分已清零.

Application was compiled for CPU type "Any." On a 32bit machine, Method 1 and Method 2 both worked, and behaved as expected. On a 64bit machine, only method 2 worked correctly. With Method 1, the application was only able to see the first element of the array. The rest of the array was zeroed out.

推荐答案

64 位框架可能会在函数调用之前复制到某个临时存储空间,然后在函数调用之后将该数据复制回原始的 'ref' 参数结束了.

The 64 bit Framework might be copying to some temporary storage space before the function call, then copying that data back out to the original 'ref' parameter after the function is finished.

这篇关于为什么(错误地)使用 ref myarray[0] 传递数组可以工作,但只能在 32 位应用程序中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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