hybridclr_unity/Editor/ReversePInvokeWrap/Generator.cs

60 lines
2.4 KiB
C#
Raw Normal View History

using HybridCLR.Editor.ABI;
using HybridCLR.Editor.Template;
2022-09-22 08:56:07 +08:00
using System;
using System.Collections.Generic;
using System.IO;
2022-09-22 08:56:07 +08:00
using System.Linq;
using System.Text;
using UnityEngine;
2022-09-22 08:56:07 +08:00
namespace HybridCLR.Editor.ReversePInvokeWrap
{
public class Generator
2022-09-22 08:56:07 +08:00
{
public void Generate(List<ABIReversePInvokeMethodInfo> methods, string outputFile)
2022-09-22 08:56:07 +08:00
{
string template = File.ReadAllText(outputFile, Encoding.UTF8);
2022-09-22 08:56:07 +08:00
var frr = new FileRegionReplace(template);
var codes = new List<string>();
int methodIndex = 0;
var stubCodes = new List<string>();
foreach(var methodInfo in methods)
2022-09-22 08:56:07 +08:00
{
MethodDesc method = methodInfo.Method;
string paramDeclaringListWithoutMethodInfoStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}"));
string paramNameListWithoutMethodInfoStr = string.Join(", ", method.ParamInfos.Select(p => $"__arg{p.Index}").Concat(new string[] { "method" }));
string paramTypeListWithMethodInfoStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()}").Concat(new string[] { "const MethodInfo*" }));
string methodTypeDef = $"typedef {method.ReturnInfo.Type.GetTypeName()} (*Callback)({paramTypeListWithMethodInfoStr})";
for (int i = 0; i < methodInfo.Count; i++, methodIndex++)
{
codes.Add($@"
{method.ReturnInfo.Type.GetTypeName()} __ReversePInvokeMethod_{methodIndex}({paramDeclaringListWithoutMethodInfoStr})
2022-09-22 08:56:07 +08:00
{{
const MethodInfo* method = MetadataModule::GetMethodInfoByReversePInvokeWrapperIndex({methodIndex});
{methodTypeDef};
{(method.ReturnInfo.IsVoid ? "" : "return ")}((Callback)(method->methodPointerCallByInterp))({paramNameListWithoutMethodInfoStr});
2022-09-22 08:56:07 +08:00
}}
");
stubCodes.Add($"\t\t{{\"{method.Sig}\", (Il2CppMethodPointer)__ReversePInvokeMethod_{methodIndex}}},\n");
}
Debug.Log($"[ReversePInvokeWrap.Generator] method:{method.MethodDef} wrapperCount:{methodInfo.Count}");
2022-09-22 08:56:07 +08:00
}
codes.Add(@"
ReversePInvokeMethodData g_reversePInvokeMethodStub[]
2022-09-22 08:56:07 +08:00
{
");
codes.AddRange(stubCodes);
2022-09-22 08:56:07 +08:00
codes.Add(@"
{nullptr, nullptr},
2022-09-22 08:56:07 +08:00
};
");
frr.Replace("CODE", string.Join("", codes));
2022-09-22 08:56:07 +08:00
frr.Commit(outputFile);
}
}
}