Whats up with [DllImport ("__Internal")] on Android?

So Android docs says that you need to use [DllImport (“__Internal”)] when callling C/C++ plugins:

But I know in some cases I most definitely am not doing this. I am calling C/C++ methods in .aar files by putting the libname in place of __Internal. Why does that work? Is this documentation out of date or is there something else I am missing?

This is purely a hunch: I think all the C/C++ code and the Unity engine wrapper code, all the libraries, the IL2CPP code for your scripts, as well as all the engine-built data, are all just tossed into a massive whirlpool of an Android Studio project.

Then an invocation along the lines of “Please Gradle, I beseech you build this for me…” and then out comes an APK.

If you’re lucky.

But seriously, even if it works another way, why not make it work the way the docs say? That other way by letting the library be named might mysteriously fail on certain Android targets, or might stop working in future builds of Unity.

“When in Rome…”

Just noticed actually my android build was not even building with __Internal, it gets linker errors in il2cpp. Seems to me like you would never use __Internal?

I comes down to how you put your native code into Unity project.
If you put C/C++ files or precompiled static libraries (.a files), then your native code will be linked together with il2cpp generated code, so you have to use __Internal as dll name.
However, if you compile and link your native code into a shared library (.so file) and then put that file into Unity project (directly, as part of .aar, or as part of Android Library project), then the native code will be in that shared library, you have to use library name (IIRC, you drop “lib” prefix and for sure you remove “.so” suffix), il2cpp generated code will load that library and search for a function in it.

3 Likes