当64位编译P / Inovke参数偏移了32位 [英] P/Inovke parameters offset by 32 bits when compiled in 64 bit

查看:215
本文介绍了当64位编译P / Inovke参数偏移了32位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

跟进<一个href="http://stackoverflow.com/questions/18795876/pinvoke-byte-array-to-char-not-behaving-properly-in-64-bit">PInvoke字节数组为char行为不正常的64位。 (陈旧的问题,我的怀疑是错误的,这样的标题和descriptionwas不再合适)。

Follow up to PInvoke byte array to char not behaving properly in 64 bit. (Stale question and my suspicions were wrong, thus the title and descriptionwas unfitting).

我使用的P / Invoke来调用从C#C ++ code。我有两个C#和C ++项目设置为打造64在VS的构建配置当我运行这个程序,在P / Invoke调用的参数由32位转移如下:

I am using P/Invoke to call C++ code from C#. I have both the C# and C++ projects set to build in x64 in the build configurations of VS. when I run this program, the parameters of the P/Invoke call are shifted by 32 bits as follows

C# : |Parameter 1|Parameter 2|Parameter 3|Parameter 4|
           |           |           |           |           |
           V           V           V           V           V
C++:             |Parameter 1|Parameter 2|Parameter 3|Parameter 4|

所以,如果我通过1,2,3,4从C#端,C ++侧接收2,3,4,垃圾。

So if I pass 1,2,3,4 from the C# side, the C++ side receives 2,3,4,garbage.

我已经围绕这传递了额外的int在C#参数的前面,而不改变C ++一边工作。这抵消了参数由32位和重新调整他们的计划完美的作品。

I have worked around this by passing in an extra int in front of the C# parameters without changing the C++ side. this offsets the parameters by 32 bits and realigns them and the program works perfectly.

有谁知道是什么原因造成这种奇怪的偏移和正确的方法来纠正呢?

Does anyone know what is causing this strange offset and the proper way to correct it?

下面是一个简单的例子,说明我的方法签名

Here is a simplified example showing my method signatures

C#端:

[DllImport(@"C:\FullPath\CppCode.dll", EntryPoint = "MethodName",
CallingConvention = CallingConvention.Cdecl))]
private static extern bool MethodName(parameters);

C ++侧:

C++ side:

extern "C" __declspec(dllexport)
bool CppClass::MethodName(parameters)

我怀疑是因为参数是关闭的32位,有可能是东西,是不是真的正在做的64位正常。也许调用方法时,还有一个就是变量前通过一个隐含的指针?如果这仅仅是在C#侧以及C ++期待一个64位的指针32位指针,可能会导致这种偏移的情况,但我不知道。

I suspect that since the parameters are off by 32 bits, there might be something that isn't really being done in 64 bit properly. Perhaps when calling a method, there is an implicit pointer that is passed before the variables? If that is only a 32 bit pointer on the C# side and the C++ is expecting a 64 bit pointer, that could cause this offset situation, but I'm not sure.

推荐答案

方法名不应该是一个类的实例方法,作为第一个字节(4 x86的世界,8在64位世界),将用于在非托管世界的类实例的指针。

MethodName should not be a class instance method, as the first bytes (4 in x86 world, 8 in x64 world) will be used for the class instance pointer in the unmanaged world.

所以,它应该是一个静态方法(或C风格的方法)。

So, it should be a static method (or a C style method).

这篇关于当64位编译P / Inovke参数偏移了32位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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