Icetrack
Icetrack
CC#
Created by Icetrack on 3/6/2023 in #help
❔ IL weaving with Mono.Cecil in Unity isn't affecting Unity's assembly.
Hello, I wrote a simple program that finds methods decorated with an [Rpc] attributes, which works at finding them. Issue is when I try to weave Debug.Log("Hi"); into the method in which I'm not presented with any error but it fails. Code is below, any idea why this happens?
partial class Weaver
{
private static void RpcWeave(this MethodDefinition method)
{
Debug.Log($"RpcWeave called for method {method.Name}");
if (method.Body == null)
{
Debug.Log("Method body is null");
return;
}

if (method.Module == null)
{
Debug.Log("Method module is null");
return;
}

// Get the reference to the UnityEngine.Debug class
var debugType = method.Module.ImportReference(typeof(UnityEngine.Debug));
if (debugType == null)
{
Debug.Log("Debug class not found");
return;
}

// Get the reference to the Log method with a single string parameter
var logMethod = method.Module.ImportReference(debugType.Resolve().Methods.FirstOrDefault(m =>
m.Name == "Log" && m.Parameters.Count == 1 &&
m.Parameters[0].ParameterType.FullName == typeof(object).FullName));

// Check if the Log method was found
if (logMethod == null)
{
Debug.Log("Log method not found");
return;
}

ILProcessor weaver = method.Body.GetILProcessor();
if (weaver == null)
{
Debug.Log("ILProcessor is null");
return;
}

weaver.Emit(OpCodes.Ldstr, "Hi");
weaver.Emit(OpCodes.Call, logMethod);
weaver.Emit(OpCodes.Ret);
}

}
partial class Weaver
{
private static void RpcWeave(this MethodDefinition method)
{
Debug.Log($"RpcWeave called for method {method.Name}");
if (method.Body == null)
{
Debug.Log("Method body is null");
return;
}

if (method.Module == null)
{
Debug.Log("Method module is null");
return;
}

// Get the reference to the UnityEngine.Debug class
var debugType = method.Module.ImportReference(typeof(UnityEngine.Debug));
if (debugType == null)
{
Debug.Log("Debug class not found");
return;
}

// Get the reference to the Log method with a single string parameter
var logMethod = method.Module.ImportReference(debugType.Resolve().Methods.FirstOrDefault(m =>
m.Name == "Log" && m.Parameters.Count == 1 &&
m.Parameters[0].ParameterType.FullName == typeof(object).FullName));

// Check if the Log method was found
if (logMethod == null)
{
Debug.Log("Log method not found");
return;
}

ILProcessor weaver = method.Body.GetILProcessor();
if (weaver == null)
{
Debug.Log("ILProcessor is null");
return;
}

weaver.Emit(OpCodes.Ldstr, "Hi");
weaver.Emit(OpCodes.Call, logMethod);
weaver.Emit(OpCodes.Ret);
}

}
3 replies
CC#
Created by Icetrack on 9/1/2022 in #help
Find all methods with an attribute using GeneratorExecutionContext
Im kind of new with source generators and Im trying to find all the methods marked with my attribute but can't approach, it would love if there was way to be guided by it
81 replies