From 71294db3c143c6019c133d03f57251fd827ce84d Mon Sep 17 00:00:00 2001 From: PopSlime Date: Mon, 25 Sep 2023 17:09:27 +0800 Subject: [PATCH] Optimize GC and performance for MonoPInvokeCallback. --- .../Unity/ScopedThreadAttacherInjector.cs | 50 +++++++++++++++++++ .../ScopedThreadAttacherInjector.cs.meta | 11 ++++ 2 files changed, 61 insertions(+) create mode 100644 Assets/Cryville/Common/Unity/ScopedThreadAttacherInjector.cs create mode 100644 Assets/Cryville/Common/Unity/ScopedThreadAttacherInjector.cs.meta diff --git a/Assets/Cryville/Common/Unity/ScopedThreadAttacherInjector.cs b/Assets/Cryville/Common/Unity/ScopedThreadAttacherInjector.cs new file mode 100644 index 0000000..a668e3f --- /dev/null +++ b/Assets/Cryville/Common/Unity/ScopedThreadAttacherInjector.cs @@ -0,0 +1,50 @@ +#if UNITY_EDITOR +using System; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using UnityEditor; + +namespace Cryville.Common.Unity { + [InitializeOnLoad] + public class ScopedThreadAttacherInjector { + static readonly Encoding _encoding = new UTF8Encoding(false, true); + static string _filePath; + static string _oldSrc; + + static ScopedThreadAttacherInjector() { + BuildPlayerWindow.RegisterBuildPlayerHandler(opt => HandlePlayerBuild(opt)); + } + + static void HandlePlayerBuild(BuildPlayerOptions opt) { + try { + OnPreprocessBuild(); + BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(opt); + } + finally { + OnPostprocessBuild(); + } + } + + static void OnPreprocessBuild() { + var il2cppRoot = Environment.GetEnvironmentVariable("UNITY_IL2CPP_PATH"); + if (string.IsNullOrEmpty(il2cppRoot)) { + _filePath = string.Empty; + return; + } + _filePath = Path.Combine(il2cppRoot, "libil2cpp", "vm", "ScopedThreadAttacher.cpp"); + if (!File.Exists(_filePath)) { + _filePath = string.Empty; + return; + } + _oldSrc = File.ReadAllText(_filePath, _encoding); + File.WriteAllText(_filePath, Regex.Replace(_oldSrc, @"~\s*?ScopedThreadAttacher\s*?\(\s*?\)\s*?\{.*\}", "~ScopedThreadAttacher(){}", RegexOptions.Singleline), _encoding); + } + + static void OnPostprocessBuild() { + if (string.IsNullOrEmpty(_filePath)) return; + File.WriteAllText(_filePath, _oldSrc, _encoding); + } + } +} +#endif diff --git a/Assets/Cryville/Common/Unity/ScopedThreadAttacherInjector.cs.meta b/Assets/Cryville/Common/Unity/ScopedThreadAttacherInjector.cs.meta new file mode 100644 index 0000000..f34c5c8 --- /dev/null +++ b/Assets/Cryville/Common/Unity/ScopedThreadAttacherInjector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2322d8e9250e9e6469826361223dfdda +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: