IntPtr in 32 Bit OS, UInt64 in 64 bit OS

自闭症网瘾萝莉.ら 提交于 2019-12-24 00:24:24

问题


I'm trying to do an interop to a C++ structure from C#. The structure (in a C# wrapper) is something like this

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SENSE4_CONTEXT
{
    public System.IntPtr dwIndex; //or UInt64, depending on platform.
}

The underlying C++ structure is a bit abnormal. In 32 bit OS, dwIndex must be IntPtr in order for the interop to work, but in 64 bit OS, it must be UInt64 in order for the interop to work.

Any idea how to modify the above structure to make it work on both 32 and 64 bit OS?


回答1:


If the "dw" prefix in dwIndex is accurate then it sounds like a DWORD, which is a 32-bit unsigned integer. In that case you need to use UIntPtr, which will be like UInt32 on 32-bit and like UInt64 on 64-bit.

It seems unlikely that your C++ program requires a signed integer on a 32-bit platform and an unsigned one on a 64-bit one (though not impossible, of course).




回答2:


In a 64-bit process, an IntPtr should be marshalled exactly the same as a UInt64.
Make sure to set your Target Platform to Any CPU.

To treat it as a UInt64 in C#, you can write

UInt64 value = (UInt64)s.dwIndex.ToInt64();

If you need to run as a 32-bit process, you'll need to declare two different versions of the struct, and two different overloads of the methods that take it, and select one of them using an if statement.




回答3:


You could use a compiler directive/platform detect, then do a common typedef:

typedef indexType IntPtr

or

typedef indexType UInt64



来源:https://stackoverflow.com/questions/2846666/intptr-in-32-bit-os-uint64-in-64-bit-os

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