Call unmanaged functions from managed code
Declare a C# prototype for an unmanaged function so your managed code can call into a native plug-in.
읽는 시간 3분최근 업데이트: 하루 전
To call an unmanaged function from managed code, declare a function prototype in C# with the following characteristics:
- It has the same name as the unmanaged function.
- It has compatible parameter and return types.
- It's declared as .
static - It's declared as .
extern - It has a that identifies the native library location.
DllImportAttribute
You can place these managed declarations anywhere in your C# code. For example, you can declare them all in a single class, or declare individual functions in the separate classes that use them.
Export the unmanaged function
The unmanaged function must use C linkage. C linkage avoids name mangling and other Application Binary Interface (ABI) issues that arise with C++ linkage.
For example, a native plug-in might define the following function. You can copy this code directly into a C++ source code file in your Unity project, which Unity compiles and links statically:
#include <stdio.h>extern "C" { void SendString(const char* message) { // The output appears in the Player log file. printf("%s\n", message); fflush(stdout); }}
To build the same code as a precompiled dynamic library, you must also export each function so the dynamic loader can find it. Define an export macro and prefix each exported function with it, for example . A statically linked source code plug-in doesn't need this annotation.
EXPORT_API void SendString(...)// Select the annotation by target platform, not by compiler.// Every Windows compiler (MSVC, MinGW, and Clang) needs __declspec(dllexport) to export from a DLL.// GCC and Clang use the visibility attribute on other platforms.#if defined(_WIN32)#define EXPORT_API __declspec(dllexport)#elif defined(__GNUC__) || defined(__clang__)#define EXPORT_API __attribute__((visibility("default")))#else#define EXPORT_API#endif
Your C# class can declare the managed function prototype for the function as follows:
SendString[DllImport("__Internal")]private static extern void SendString(string message);
For more information on how to identify the native plug-in library to load, refer to DllImport attribute.