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.
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:
MyLibraryName.dll
MyLibraryName.bundle, MyLibraryName.dylib, or libMyLibraryName.dylib
libMyLibraryName.so or MyLibraryName.so
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);
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: