Simple projects to create Unity native libraries for Windows and Android
Unity native plugin
Simplest Plugin example Example code from here: https://docs.unity3d.com/Manual/PluginsForDesktop.html
Follow this tutorial
If you don't need the precompiled headers.
// SimpleNativeLibrary.cpp : Defines the exported functions for the DLL application.
//
#if _MSC_VER // this is defined when compiling with Visual Studio
#define EXPORT_API __declspec(dllexport) // Visual Studio needs annotating exported functions with this
#else
#define EXPORT_API // XCode does not need annotating exported functions, so define is empty
#endif
// Link following functions C-style (required for plugins)
extern "C"
{
// The functions we will call from Unity.
//
const EXPORT_API char* PrintHello() {
return "Hello";
}
int EXPORT_API PrintANumber() {
return 5;
}
int EXPORT_API AddTwoIntegers(int a, int b) {
return a + b;
}
float EXPORT_API AddTwoFloats(float a, float b) {
return a + b;
}
} // end of export C block
Reference guides: this, and this
#include <jni.h>
#include <string>
// Link following functions C-style (required for plugins)
extern "C"
{
// The functions we will call from Unity.
const char* PrintHello() {
return "Hello";
}
int PrintANumber() {
return 5;
}
int AddTwoIntegers(int a, int b) {
return a + b;
}
float AddTwoFloats(float a, float b) {
return a + b;
}
} // end of export C block
using UnityEngine;
using System;
using System.Runtime.InteropServices;
public class UseNativeLibrary : MonoBehaviour {
//Lets make our calls from the Plugin
[DllImport("SimpleNativeLibrary")]
private static extern int PrintANumber();
[DllImport("SimpleNativeLibrary")]
private static extern IntPtr PrintHello();
[DllImport("SimpleNativeLibrary")]
private static extern int AddTwoIntegers(int i1, int i2);
[DllImport("SimpleNativeLibrary")]
private static extern float AddTwoFloats(float f1, float f2);
// Use this for initialization
void Start()
{
Debug.Log(PrintANumber());
Debug.Log(Marshal.PtrToStringAuto(PrintHello()));
Debug.Log(AddTwoIntegers(2, 2));
Debug.Log(AddTwoFloats(2.5F, 4F));
}
// Update is called once per frame
void Update () {
}
}