hybridclr_unity/Editor/ReversePInvokeWrap/Generator.cs

58 lines
2.3 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.Linq;
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(string template, PlatformABI abi, List<ABIReversePInvokeMethodInfo> methods, string outputFile)
2022-09-22 08:56:07 +08:00
{
template = template.Replace("{PLATFORM_ABI}", ABIUtil.GetHybridCLRPlatformMacro(abi));
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}"));
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($@"
void __ReversePInvokeMethod_{methodIndex}({paramDeclaringListWithoutMethodInfoStr})
2022-09-22 08:56:07 +08:00
{{
const MethodInfo* method = MetadataModule::GetMethodInfoByReversePInvokeWrapperIndex({i});
{methodTypeDef};
((Callback)(method->methodPointerCallByInterp))({paramNameListWithoutMethodInfoStr}, method);
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);
}
}
}