Search code examples
c++-clitype-conversioninteger-overflow

Convert Object to the C++ built-in type


I have the following minimal code:

using namespace System;

long get_prop( Object^ v )
{
    return Convert::ToInt32( v );
}

int main()
{
    Object^ o1 = gcnew Int32( -1 );
    Object^ o2 = gcnew UInt32( 0xFFFFFFFF );
    long value1 = get_prop( o1 );
    long value2 = get_prop( o2 );

    return 0;
}

It gives the OverflowException exception in get_prop function. In the end I need to use the result of get_prop in pure C++ code. What is the correct way to write get_prop function so it can work without exception in both cases. Can I use some sort of templates as in C++ or there more trivial solution?


Solution

  • Hmya, you are trying to stuff a 32-bit pig in a 31-bit poke. This code ends up calling Convert::ToInt32(UInt32 value) which looks like this:

    public static int ToInt32(uint value)
    {
        if (value > 0x7fffffff)
        {
            throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
        }
        return (int) value;
    }
    

    Kaboom. Not sure what kind of overflow behavior you want, but this lets the compiler do the ignoring and avoids the exception:

    long get_prop( Object^ v )
    {
        return (long)Convert::ToInt64( v );
    }