Using arrays with CLR interop

Currently there is no way to pass X++ native arrays to CLR arrays and vice versa. Even it were possible, it would be problematic because the native arrays do not support reference types: You cannot declare arrays of classes.

One solution would be to use the Axapta Foundation Class Array type to do this, but that is currently not possible. So, if you have to transfer arrays to CLR methods (and return values from them) what do you do?

You create a System.Array object instance to pass instead. Use the code below, where an array of bytes is created for inspiration (the code was originally created by Alexey Ovsyannikov).

static void Job2(Args _args)
{
    System.Type typeOfByte;
    System.Array arrayOfByte;
    int arrayOfByteLength = 8;
    int i;
    ;

typeOfByte = System.Type::GetType("System.Byte");
    arrayOfByte = System.Array::CreateInstance( typeOfByte, arrayOfByteLength );

    for( i = 0; i < arrayOfByteLength; ++i )
    {
        arrayOfByte.SetValue( System.Convert::ToByte(i), i ); // SetValue takes Object - need to cast explicitely
    }

for( i = 0; i < arrayOfByteLength; ++i )
    {
        print ClrInterop::getAnyTypeForObject( arrayOfByte.GetValue( i ) );
    }

    pause;
}

Tags: CLR-Interop