Import unmanaged functions as C# methods
Use the DllImport attribute to tell the scripting runtime which native library contains an unmanaged function on each platform.
읽는 시간 2분최근 업데이트: 6일 전
Apply the 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.
DllImportAttributeDllImportAttributeSystem.Runtime.InteropServicesusing System.Runtime.InteropServices;static externIdentify 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 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 in the following files:
libMyLibraryName- Windows:
MyLibraryName.dll - macOS: ,
MyLibraryName.bundle, orMyLibraryName.dyliblibMyLibraryName.dylib - Linux: or
libMyLibraryName.soMyLibraryName.so - Android:
libMyLibraryName.so
This scheme lets you specify the base library name in and load the library successfully on multiple platforms. You can also specify the exact file name, including the extension.
DllImportAttributeThe 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 file:
.bundle[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 , with two leading underscore characters, as the value:
__InternalDllImportAttribute[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.