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

DllImport attribute

Use the DllImportAttribute to identify where the scripting runtime can find the unmanaged function. For dynamically loaded libraries, which are loaded at runtime, use the name of the library file in the attribute. If you omit the file extension and the “lib” prefix used on POSIX platforms, the library is loaded based on platform conventions:

  • Windows: add the .dll file extension. For example, load “MyLibraryName” as “MyLibraryName.dll”.

  • POSIX (macOS, iOS, Android, etc.): add common file extensions (.so, .dll, .dylib, .bundle) and try with and without the lib prefix. For example, load “MyLibraryName” as:

    • MyLibraryName.bundle, libMyLibraryName.bundle
    • MyLibraryName.dll, libMyLibraryName.dll
    • MyLibraryName.dylib, libMyLibraryName.dylib
    • MyLibraryName.so, libMyLibraryName.so

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

The following example works across platforms (assuming you have added the necessary library files for each platform to your Unity project):

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

The following only works on macOS and Apple’s mobile platforms because it explicitly specifies a .bundle file:

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

For statically linked libraries and source code plug-insA set of code created outside of Unity that creates functionality in Unity. There are two kinds of plug-ins you can use in Unity: Managed plug-ins (managed .NET assemblies created with tools like Visual Studio) and Native plug-ins (platform-specific native code libraries). More info
See in Glossary
, use the string, __Internal (with two leading underscore characters), for the DllImportAttribute value:

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

Notes:

  • Unity only supports static linking of precompiled libraries on Android and Apple mobile platforms.
  • Unity only supports source-code plug-ins when you use the IL2CPPA Unity-developed scripting back-end which you can use as an alternative to Mono when building projects for some platforms. More info
    See in Glossary
    scripting backendA framework that powers scripting in Unity. Unity supports three different scripting backends depending on target platform: Mono, .NET and IL2CPP. Universal Windows Platform, however, supports only two: .NET and IL2CPP. More info
    See in Glossary
    .
Call managed functions from unmanaged code
Pass data between managed and unmanaged code