Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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. On a 32-bit OS, dwIndex must be IntPtr in order for the interop to work, but on a 64-bit OS, it must be UInt64 in order for the interop to work.

How can I modify the above structure to make it work on both a 32-bit and 64-bit OS?

Are you talking about the operating system, regardless of whether you're running in WOW64 or not? Because in a 32-bit process, IntPtr will be 32-bit and 64-bit in a 64-bit process... – Dean Harding May 17, 2010 at 4:30 @codeka, I'm talking about 32 or 64 bit process. I want to run as 32 bit process on 32 bit OS, and 64 bit process on 64 bit OS. – Graviton May 17, 2010 at 4:38

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

A DWORD type is a 32-bit unsigned integer regardless of whether or not the OS is 32 or 64 bit. – JaredPar May 17, 2010 at 6:31

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.

Do you mean it needs to be unsigned? In that case, you can use UIntPtr: msdn.microsoft.com/en-us/library/… – Dean Harding May 17, 2010 at 4:31 SLaks is correct. To interop there is no difference between a UInt64 and an IntPtr on a 64 bit process. – Josh May 17, 2010 at 4:36

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

typedef indexType IntPtr

typedef indexType UInt64

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.