Version: Unity 7.0 Alpha (7000.0)
Language : English
Structures, classes, and unions
Strings

NativeArrays

NativeArray<T> and other types in the Unity.Collections namespace store data in memory that isn’t managed by the scripting runtime. When you pass a pointer to this data to native code, you don’t have to pin the buffer in memory. However, you still need to consider the memory lifetime of the data, which is determined by the allocator you use. For more information on the available allocators and how they compare, refer to Introduction to allocators.

The layout of a NativeArray struct is an internal detail, so you can’t control how its fields are marshalled. However, you can pass a pointer to the buffer inside the array using an explicit pointer in an unsafe context.

Use unsafe to get an array pointer

Use the NativeArray.GetUnsafePtr method or the NativeArrayUnsafeUtility class to get a pointer to the buffer in a NativeArray. When you pass the pointer to an unmanaged function, you can treat it like a C array.

The following example is an unmanaged function that takes an array of Color (unsigned 32-bit integers) as a parameter:

typedef int32_t Color;

extern "C" {
    void CheckerFill(Color* texture, int width, int height, int numSquares, const Color colors[], int numColors) {

        const int squareSize = width / numSquares;

        for (int y = 0; y < height; ++y) {
            for (int x = 0; x < width; ++x) {
                // Select a palette entry, staying within the bounds of the colors array
                const int colorIndex = ((y / squareSize) + (x / squareSize)) % numColors;
                texture[y * width + x] = colors[colorIndex];
            }
        }
    }
}

Note: Refer to Call unmanaged functions from managed code for information about the annotations needed to compile and call functions such as this as part of a dynamically loaded library.

You can pass a pointer to a NativeArray’s buffer to this function. Using pointers in C# requires an unsafe context. Refer to Compiling unsafe C# code for information about enabling unsafe code compilation in Unity.

The following code demonstrates how to call the unmanaged CheckerFill function. The example performs the following steps:

  1. Gets a NativeArray containing the pixel data of a Texture2D object.
  2. Gets a pointer to the NativeArray buffer with GetUnsafePtr.
  3. Calls the unmanaged, CheckerFill, function to fill the texture with a checker pattern.
  4. Applies the result to the Texture2D object.
using UnityEngine;
using Unity.Collections;
using System.Runtime.InteropServices;
using Unity.Collections.LowLevel.Unsafe;

public class NativeArrayExamples
{
    // Change DllImport to use library name for
    // precompiled, dynamically linked libraries.
    [DllImport("__Internal")]
    static extern unsafe void CheckerFill(Color32* pixelDataPtr, int width, int height, int squares, [In] Color32[] colors, int numColors);

    public static void FillTextureWithCheckerboard(Texture2D texture, Color32 one, Color32 two, int squaresPerSide)
    {
        unsafe
        {
            // Get the pixel data as a NativeArray
            NativeArray<Color32> pixelData = texture.GetPixelData<Color32>(0);
            // Get a pointer to the NativeArray's buffer
            void* pixelBuffer = pixelData.GetUnsafePtr();
            // The color palette to choose from
            var palette = new Color32[] { one, two };
            // Call the unmanaged function, passing the palette length so it stays within the colors array
            CheckerFill((Color32*)pixelBuffer, texture.width, texture.height, squaresPerSide, palette, palette.Length);
            // Apply the changes to the texture
            texture.Apply(false);
        }
    }
}

Note: To safely access an array from C++ code, you must pass the number of elements it contains. In this example, the code passes numColors (the length of the color palette) so the function never reads past the end of the colors array. The texture array length can be calculated from the width and height parameters, so the length isn’t passed explicitly in this example.

Demonstration

You can use the following MonoBehaviour class to call the FillTextureWithCheckerboard method in the NativeArrayExamples class from the previous example. The example adds two GameObject primitives to the scene with textures generated using the unmanaged CheckerFill function.

using UnityEngine;

public class DemoNativeArray : MonoBehaviour
{
    void Start()
    {
        AddCheckeredObject(PrimitiveType.Sphere, Color.blue,  Color.yellow, Vector3.zero);
        AddCheckeredObject(PrimitiveType.Cube, Color.red,  Color.white, Vector3.one);
    }

    void AddCheckeredObject(PrimitiveType primitive, Color colorOne, Color colorTwo, Vector3 position)
    {
        // Create a new texture
        Texture2D checkerboard = new Texture2D(256, 256, TextureFormat.RGBA32, false);
        // Fill the texture with a checkerboard pattern using the NativeArrayExamples class
        NativeArrayExamples.FillTextureWithCheckerboard(checkerboard, colorOne, colorTwo, 8);

        var go = GameObject.CreatePrimitive(primitive);
        go.transform.position = position;

        var litShader = Shader.Find("Universal Render Pipeline/Lit");
        if (litShader != null)
        {
            // Create a new material using the URP Lit shader
            Material material = new Material(litShader);
            // Assign the texture to the material
            material.SetTexture("_BaseMap", checkerboard);
            go.GetComponent<MeshRenderer>().material = material;
        }
        else
            Debug.LogError("Unable to load the Universal Render Pipeline/Lit shader.");
    }
}

Notes:

  • The example requires IL2CPP and doesn’t work in Play mode when you use [DllImport("__Internal")]. To run the example in Play mode, you can compile the unmanaged example code as a library and change the DLLImport statements to use the library name. For more information, refer to DllImport attribute.
  • The demonstration loads the URP Lit shader at runtime. The build process strips unused shaders and variants from a build, and can’t detect runtime usage such as this. The easiest workaround to run this example is to add a primitive object to the scene before building.
  • Texture2D.GetPixelData<T> returns a NativeArray that points to the texture’s existing memory. It doesn’t allocate memory, so you don’t need to dispose the NativeArray. Disposing it has no effect.

Additional resources

Structures, classes, and unions
Strings