Why does (incorrectly) using ref myarray[0] to pass in an array work, but only in 32bit Applications?

雨燕双飞 提交于 2019-12-11 02:38:15

问题


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

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.

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.


回答1:


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.




回答2:


My guess would be that you're loading different versions of the dll itself... a 64-bit application can't load the same 32-bit version of the dll that was loaded when running as x86, so you have to be pointing to a different dll. The 64-bit version of the dll must be handling the parameters in a different manner.

What DLL are you loading? Would it be something handled by WinSxs?



来源:https://stackoverflow.com/questions/4147423/why-does-incorrectly-using-ref-myarray0-to-pass-in-an-array-work-but-only-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!