Вопрос

if I wish to marshal an int in C# (Int32) to/from a native (C++) library, what's the best way to declare the relevant variable in C++ code?

I could use a standard int but I'd rather be explicit about the width of that variable (I know that it's 32-bit on most platforms anyway).

So far, I can see two options:

  • int32_t in <cstdint>
  • __int32 (MSVC++ identifier) ... However I'd like to remain platform independent if I can

I seem to recall hearing that C++11 has some new library for this, but I can't seem to find any mention of it.

Thank you.

Это было полезно?

Решение

The int keyword in the currently shipping C# and C++ compilers are type aliases, respectively for System.Int32 and __int32, the concrete types used by their back-ends. I've been writing code for 30 years and have used 8-bit, 16-bit, 32-bit and 64-bit processors. And used int 30 years ago like I do today. And expended very little effort to port programs to the next generation architecture or operating system version.

You see this back in the winapi as well. Every type used for a function argument or return value is a type alias. The CreateWindow() function in Windows version 1.0 looks exactly the same as the one you use in the 64-bit version of Windows 8.1

I have no illusion that this progression suddenly stopped today. 128-bit processors are already the bread-and-butter for IBM. Languages use type aliases to prevent themselves from becoming rapidly outdated and forgotten. True for languages like C and C++, true for C# as well. Although it certainly is going to require moving a bigger rock in the case of C#, the identity is engraved in most any C# programmer's mind right now.

Intentionally not using type aliases makes your program less portable.

Другие советы

You can use int32_t which is exactly 32 bits. It is possible for there to be a C++ implementation for which int32_t is not defined, but in that case, all bets are off.

On every platform that I know of which supports C#, then C/C++ int is 32 bits and so you may be over-thinking this.

Another thing to consider is what type your C++ code accepts. If it accepts int, and you use a platform where int is not 32 bits, then you still have a problem.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top