Skip to content

Instantly share code, notes, and snippets.

@paulhayes
Last active February 21, 2024 14:00
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save paulhayes/06435c009d8ae2d305cc7d9e2f6cc1b7 to your computer and use it in GitHub Desktop.
Save paulhayes/06435c009d8ae2d305cc7d9e2f6cc1b7 to your computer and use it in GitHub Desktop.
Runtime loading dlls in Unity3d
using System;
using UnityEngine;
public class DllLoadingAtRuntimeExample : MonoBehaviour
{
static IntPtr nativeLibraryPtr;
delegate int MultiplyFloat(float number, float multiplyBy);
delegate void DoSomething(string words);
void Awake()
{
if (nativeLibraryPtr != IntPtr.Zero) return;
nativeLibraryPtr = Native.LoadLibrary("MyNativeLibraryName");
if (nativeLibraryPtr == IntPtr.Zero)
{
Debug.LogError("Failed to load native library");
}
}
void Update()
{
Native.Invoke<DoSomething>(nativeLibraryPtr, "Hello, World!");
int result = Native.Invoke<int, MultiplyFloat>(nativeLibraryPtr, 10, 5); // Should return the number 50.
}
void OnApplicationQuit()
{
if (nativeLibraryPtr == IntPtr.Zero) return;
Debug.Log(Native.FreeLibrary(nativeLibraryPtr)
? "Native library successfully unloaded."
: "Native library could not be unloaded.");
}
}
/*
* Native dll invocation helper by Francis R. Griffiths-Keam
* www.runningdimensions.com/blog
*/
using System;
using System.Runtime.InteropServices;
using UnityEngine;
public static class Native
{
public static T Invoke<T, T2>(IntPtr library, params object[] pars)
{
IntPtr funcPtr = GetProcAddress(library, typeof(T2).Name);
if (funcPtr == IntPtr.Zero)
{
Debug.LogWarning("Could not gain reference to method address.");
return default(T);
}
var func = Marshal.GetDelegateForFunctionPointer(GetProcAddress(library, typeof(T2).Name), typeof(T2));
return (T)func.DynamicInvoke(pars);
}
public static void Invoke<T>(IntPtr library, params object[] pars)
{
IntPtr funcPtr = GetProcAddress(library, typeof(T).Name);
if (funcPtr == IntPtr.Zero)
{
Debug.LogWarning("Could not gain reference to method address.");
return;
}
var func = Marshal.GetDelegateForFunctionPointer(funcPtr, typeof(T));
func.DynamicInvoke(pars);
}
[DllImport("kernel32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
}
@yogeshpatel4all
Copy link

Can you also paste the DLL function code or DLL and solution or file. I am not able to call the functions. LIbrary is loaded, but functions its not calling.

@paulhayes
Copy link
Author

I'm afraid I worked on this a while ago, I don't have a suitable example library to hand. You'll have to search elsewhere, have a read of the blog where I got this code from: http://runningdimensions.com/blog/?p=5

@plaidpants
Copy link

Seems to load the DLL and I am able to execute the DLL functions with the Native.Invoke call but when I unload the DLL Unity exits which is not so helpful.

@paulhayes
Copy link
Author

I think I've encountered this and didn't find a proper solution. Let me know if you figure it out.

@plaidpants
Copy link

I've been able to get it not to occur if I try to make sure nothing is accessing the DLL at the time of quitting. In my case I have a separate thread started using a function in the DLL, originally I was exiting the thread prior to quitting but maybe not quick enough, I added a forever wait "while (thread.IsAlive == true) ;" in the OnApplicationQuit() function prior to attempting to the call to Native.FreeLibrary() and it appear to unload cleanly now.

@paulhayes
Copy link
Author

That's really useful info.

@plaidpants
Copy link

Any ideas how I could make this work on Android, I am currently patching a file to create the library at runtime and then loading it and would like to do the same on android.

@paulhayes
Copy link
Author

That sounds impossible on Android. Can you let me know more about what the code of your compiling at runtime? What does it do, and why does it need to be changed?

@plaidpants
Copy link

plaidpants commented Apr 18, 2022

Project is here, it also uses this , I create a modified version of the original EXE in DLL format and then create a bps patch file based on the original EXE, this patch file is then used to patch the original EXE into a DLL at launch which the game then loads at runtime. This way, all the original EXE tables, text, etc. are preserved and my new 64-bit DLL code is swapped in to replace the old 32-bit EXE code. I can then run the original game engine in Unity without having to include any intellectual property from the original EXE. Currently this is working for Windows but if I want to get it working on the Oculus Quest I need to do the same on Android.

@paulhayes
Copy link
Author

🤯 Wow, that is incredible work. If I have any ideas I'll suggest them.

@plaidpants
Copy link

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment