On my System: sizeof(long) in c++开发者_运维知识库 is 4 aka 32bits sizeof(long) in c# is 8 aka 64 bits
So in my Interop method declarations I've been substituting c++ longs with c# int's however I get the feeling this isn't safe?
Why is a long the same size as an int in c++? And long long is 64bits? What's next a long long long long??
Best thing to do assuming you have a recent C library is to include <stdint.h>
and use uint64_t
, int64_t
, uint32_t
, int32_t
. This will works regardless of model of the underlying platform.
But if you are curious, the underlying issue is that different systems use different models. On 32 bit systems, both Posix and Windows use ILP32, which means an integer, long and point are all 32 bits long.
For 64 bits, Posix and Windows use different models.
Posix usually uses LP64 which means 32 bit integers, 64 bit longs and 64 bit pointers.
Windows uses LLP64 which means 32 bit integers and longs, 64 bit long longs and 64 bit pointers.
Yes it is safe, as long as they aren't platform-sized integers (e.g. 32-bit for x86 platform and 64-bits for x64-platforms), in which case you'd use an IntPtr
.
Don't forget that at the time C(++) was defined, the default computation size wasn't 32 bits. So 32 bits was defined as "long". However, the newer programming languages have adopted the new default sizes.
On most platforms C++ long
is the same as int
and is 4 bytes. This was a remainder of the 16bit days when int
was 2 bytes and long was double word - i.e. 4 bytes.
So if your C++ platform relied on 32bit longs, converting those to C# int
is plenty safe.
精彩评论