Created
November 10, 2022 10:15
-
-
Save juj/56da028de9e5768d8d22ee1a431dd36f to your computer and use it in GitHub Desktop.
Unity JS -> C# new array allocation marshalling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
using UnityEngine; | |
public class code : MonoBehaviour | |
{ | |
void Start() | |
{ | |
Method1(); | |
Method2(); | |
} | |
// Method 1: malloc() memory on JS side, use IntPtr and Marshal.ReadIntPtr() | |
// and call back to JS side to free() to avoid memory leak | |
// https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.readintptr?view=net-7.0 | |
[DllImport("__Internal")] | |
public static extern IntPtr GetBytes(out int arrayLength); | |
[DllImport("__Internal")] | |
public static extern void nativeFree(IntPtr nativeArray); | |
void Method1() | |
{ | |
int arrayLength; | |
IntPtr array = GetBytes(out arrayLength); | |
Debug.Log($"Received array of length {arrayLength}"); | |
for(int i = 0; i < arrayLength; ++i) | |
Debug.Log($"{i}: {Marshal.ReadIntPtr(array, i<<2)}"); | |
nativeFree(array); // Careful to avoid memory leak! | |
} | |
// Method 2: malloc() memory on JS side, use IntPtr and Marshal.Copy() | |
// and call back to JS side to free() to avoid memory leak | |
// https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.copy?view=net-7.0 | |
void Method2() | |
{ | |
int arrayLength; | |
IntPtr array = GetBytes(out arrayLength); | |
Debug.Log($"Received array of length {arrayLength}"); | |
int[] csArray = new int[arrayLength]; | |
Marshal.Copy(array, csArray, 0, arrayLength); | |
nativeFree(array); // Careful to avoid memory leak! | |
foreach(int i in csArray) | |
Debug.Log(i.ToString()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mergeInto(LibraryManager.library, { | |
GetBytes: function(arrayLength) { | |
var len = (1 + Math.random() * 16) | 0; | |
var array = _malloc(len<<2); | |
for(var i = 0; i < len; ++i) HEAPU32[(array>>2)+i] = i; | |
HEAPU32[arrayLength>>2] = len; | |
return array; | |
}, | |
nativeFree: function(nativeArray) { | |
_free(nativeArray); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment