Lesson 117 +10 XP

Native Plugins and P/Invoke

Native Plugins and P/Invoke

Native plugins allow Unity projects to call compiled C/C++ libraries, access platform-specific native APIs, or run performance-critical code.

Managed vs Native Plugins

  • Managed Plugins: Compiled C# assemblies (.dll). They only access standard .NET APIs and are placed in the Assets folder.
  • Native Plugins: Platform-specific compiled libraries (.dll, .so, .bundle, .a). They run outside the C# virtual machine.

Calling Native C Functions (P/Invoke)

Compile your C library to a dll/so file:

// MyLibrary.c
extern "C" {
    int AddNumbers(int a, int b) {
        return a + b;
    }
}

Import and call the function in your C# Unity script:

using System.Runtime.InteropServices;
using UnityEngine;

public class NativeBridge : MonoBehaviour
{
    // Imports MyLibrary.dll (Windows), libMyLibrary.so (Android/Linux), or MyLibrary.bundle (macOS)
    [DllImport("MyLibrary")]
    private static extern int AddNumbers(int a, int b);

    void Start()
    {
        int total = AddNumbers(15, 25);
        Debug.Log("Result from native DLL: " + total); // 40
    }
}

Folder Architecture for Native Libraries

For Unity to build and deploy native plugins correctly, place them in platform-specific subfolders inside Assets/Plugins:

  • Windows: Assets/Plugins/x86_64/MyLibrary.dll
  • Android: Assets/Plugins/Android/libs/arm64-v8a/libMyLibrary.so
  • iOS: Assets/Plugins/iOS/libMyLibrary.a (using [DllImport("__Internal")])

TL;DR

  • Import native functions using [DllImport("PluginName")].
  • Declare methods with private static extern.
  • Keep library files inside designated Assets/Plugins platform folders.