Version: Unity 6.0 (6000.0)
Language : English
Call managed functions from unmanaged code
Pass data between managed and unmanaged code

Import unmanaged functions as C# methods

Apply the DllImportAttribute to a method to identify an unmanaged library to import an external function from. The value you pass to the attribute depends on whether you link the native code dynamically or statically.

DllImportAttribute is a .NET attribute in the System.Runtime.InteropServices namespace. It isn’t part of the Unity API. To use it, add using System.Runtime.InteropServices; at the top of your C# script, then apply the attribute to a static extern method declaration.

Identify a dynamically linked library

For dynamically linked libraries, which load at runtime, use the name of the library file in the attribute. Unity first tries the name exactly as you specify it. If you omit the file extension, or the lib prefix that non-Windows platforms use, Unity also tries the file name variations that the platform conventions use. For example, Unity finds a library that you specify as MyLibraryName in the following files:

  • Windows: MyLibraryName.dll
  • macOS: MyLibraryName.bundle, MyLibraryName.dylib, or libMyLibraryName.dylib
  • Linux: libMyLibraryName.so or MyLibraryName.so
  • Android: libMyLibraryName.so

This scheme lets you specify the base library name in DllImportAttribute and load the library successfully on multiple platforms. You can also specify the exact file name, including the extension.

The following declaration works across platforms, if you add the necessary library files for each platform to your Unity project:

[DllImport("SimpleMath")]
static extern float AddTwoFloats(float f1, float f2);

The following declaration works only on macOS, because it explicitly specifies a .bundle file:

[DllImport("libStringUtilities.bundle")]
static extern void SendStringArray([In] string[] strings, int length);

Identify a statically linked library or source code plug-in

For statically linked libraries and source code plug-ins, use the string __Internal, with two leading underscore characters, as the DllImportAttribute value:

[DllImport("__Internal")]
static extern int AddTwoIntegers(int i1, int i2);

The following limitations apply:

  • Unity supports static linking of precompiled libraries on Android, Apple mobile platforms, and the Web platform, but not on desktop platforms.
  • Unity supports source code plug-ins only when you use the IL2CPP scripting backend. Source code plug-ins don’t work in the Unity Editor or in Play mode.

Additional resources

Call managed functions from unmanaged code
Pass data between managed and unmanaged code