I have created a C++ library using android studio to add , subtract and print functions in android studio. Followed unity’s managed plugins for android documentation for this.
I was able to create a .aar file while building the android studio project and extracted the .aar file to get .so files. ( Unity Version - 2023.3.13f1)
I have placed it inside Assets/Plugins/Android/arm64-v8a,armeabi-v7a.
Please see my CPP and C# script below
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_nativelib_NativeLib_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
extern "C" JNIEXPORT jint JNICALL
Java_com_example_nativelib_NativeLib_addNumbersFromJNI(
JNIEnv* env,
jobject /* this */,
jint num1,
jint num2) {
// Add two numbers
jint result = num1 + num2;
return result;
}
extern "C" JNIEXPORT jint JNICALL
Java_com_example_nativelib_NativeLib_subtractNumbersFromJNI(
JNIEnv* env,
jobject /* this */,
jint num1,
jint num2) {
// Subtract two numbers
jint result = num1 - num2;
return result;
}
c# bridge
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
public class NativePlugin : MonoBehaviour
{
const string LibFile = "nativelib";
[DllImport(NativePlugin.LibFile)]
private static extern string stringFromJNI();
[DllImport(NativePlugin.LibFile)]
private static extern int addNumbersFromJNI(int num1, int num2);
[DllImport(NativePlugin.LibFile)]
private static extern int subtractNumbersFromJNI(int num1, int num2);
private void OnGUI()
{
GUILayout.Label("Result String: " + stringFromJNI());
GUILayout.Label("Add: " + addNumbersFromJNI(5, 3));
GUILayout.Label("Subtract: " + subtractNumbersFromJNI(5, 3));
}
}
I am getting DLL nativelib unable to find exception
I followed the thread related to similar problem,
NativePlugin c++ Android sample and self build pcl not loading,Native Plugins c++ "dll not found"
But my problem is not sorted out, What is the right approach. I also tried to create a plugin using visual studio c++ Shared android library, the approach worked for windows build but the .so file generated for android is throwing the same DLL unable to find exception.
NB: Selected IL2CPP support and enabled Unsafe code options, changed the bundle identifier exactly to the library package name