hattenn
hattenn

Reputation: 4399

Is it safe to have an external function from unmanaged code that returns an int

[DllImport(MyUnmanagedLibrary, CallingConvention = CallingConvention.Cdecl)]
internal static extern int MyFunction();

Let's say this is a function that I import from an unmanaged C++ library. In this instance the external function is declared as returning an int. The size of int does not change in managed C# code, but it does change depending on the architecture in unmanaged C++ code. Is it safe to assume that it returns an int? Should I use IntPtr instead, as the return value? Or something else?

Upvotes: 4

Views: 147

Answers (2)

blackmath
blackmath

Reputation: 252

You need to set the compiler option with "-m32" or "-m64" for g++ for example. More specific choose the best match based on your "Machine Dependent Options"

Upvotes: 0

Matteo Italia
Matteo Italia

Reputation: 126807

int in C# is and will always be System.Int32, the point is that every C++ compiler is (in theory) free to do whatever it wants with types sizes (within certain limits), so, if you want to avoid a mismatch, you should change the C++ side of code, making it return a fixed-size integer (e.g. int32_t). IntPtr cannot help, since int is not defined to have the size of a pointer (and actually, on x86_64 Windows int is 32 bit, while int * is 64 bit).

On the other hand, it's extremely unlikely that any compiler on x86 Windows will ever define int as anything different than a 32 bit 2's-complement integer, for obvious binary compatibility reasons.

Upvotes: 5

Related Questions