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

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

问题描述

跟进 PInvoke 字节数组到char 在 64 位中行为不正常.(陈旧的问题和我的怀疑是错误的,因此标题和描述不合适).

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++ 代码.我在 VS 的构建配置中将 C# 和 C++ 项目设置为在 x64 中构建.当我运行这个程序时,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|

所以如果我从 C# 端传递 1,2,3,4,C++ 端会收到 2,3,4,garbage.

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

我通过在 C# 参数前面传递一个额外的 int 来解决这个问题,而不改变 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:FullPathCppCode.dll", EntryPoint = "MethodName",
CallingConvention = CallingConvention.Cdecl))]
private static extern bool MethodName(parameters);

C++ 端:

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

我怀疑由于参数被 32 位关闭,因此可能有些事情在 64 位中没有正确完成.也许在调用方法时,在变量之前传递了一个隐式指针?如果这只是 C# 端的 32 位指针,而 C++ 需要 64 位指针,则可能会导致这种偏移情况,但我不确定.

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.

推荐答案

MethodName 不应是类实例方法,因为第一个字节(x86 世界中的 4 个,x64 世界中的 8 个)将是用于非托管世界中的类实例指针.

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).

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

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