Skip to content

Instantly share code, notes, and snippets.

@thebne
Created December 15, 2023 22:46
Show Gist options
  • Save thebne/63bc289a0db882230c953dce74c7b295 to your computer and use it in GitHub Desktop.
Save thebne/63bc289a0db882230c953dce74c7b295 to your computer and use it in GitHub Desktop.
Unity: Mono StackFrame with 0 allocations
private readonly struct FrameData : IEquatable<FrameData>
{
public readonly MethodBase method;
public readonly int lineNumber;
public readonly int columnNumber;
// mono internal
private static readonly MethodInfo get_frame_info_methodInfo
= typeof(StackFrame).GetMethod("get_frame_info", BindingFlags.Static | BindingFlags.NonPublic);
private delegate bool get_frame_info(int depth, bool fileInfo, ref MethodBase methodBase,
ref int offset, ref int ilOffset, ref string fileName, ref int lineNumber, ref int columnNumber);
private static readonly get_frame_info get_frame_info_delegate
= (get_frame_info)Delegate.CreateDelegate(typeof(get_frame_info), get_frame_info_methodInfo);
public FrameData(int depth) : this()
{
int offset = 0, ilOffset = 0;
string fileName = null;
get_frame_info_delegate(depth, false, ref method, ref offset, ref ilOffset,
ref fileName, ref lineNumber, ref columnNumber);
}
public override string ToString()
{
var sb = new StringBuilder();
if (method != null)
{
if (method.DeclaringType != null)
sb.Append(method.DeclaringType.FullName);
sb.Append(".");
sb.Append(method.Name);
}
else
{
sb.Append("(unknown)");
}
if (lineNumber != 0)
{
sb.Append(":");
sb.Append(lineNumber);
}
return sb.ToString();
}
public override int GetHashCode()
{
return HashCode.Combine(method, lineNumber, columnNumber);
}
public bool Equals(FrameData other)
{
return method == other.method && lineNumber == other.lineNumber && columnNumber == other.columnNumber;
}
public override bool Equals(object obj)
{
return obj is FrameData other && Equals(other);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment