Skip to content

Commit

Permalink
Runtime: Use attribute to find factory method.
Browse files Browse the repository at this point in the history
  • Loading branch information
badcel committed Aug 9, 2021
1 parent a6b6123 commit d73171b
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 12 deletions.
16 changes: 16 additions & 0 deletions Libs/GObject-2.0/Classes/ConstructAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;

namespace GObject
{
/// <summary>
/// This attribute can be used to give the runtime
/// an alternative constructor method. This is
/// usefull if a constructor should return a
/// more derived type than the constructor itself.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class ConstructAttribute : Attribute
{

}
}
16 changes: 6 additions & 10 deletions Libs/GObject-2.0/Native/Classes/BoxedWrapper.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using GLib;

namespace GObject.Native
{
Expand Down Expand Up @@ -44,13 +42,11 @@ public static object WrapHandle(IntPtr handle, Type gtype)

private static MethodInfo? GetSecretFactoryMethod(System.Type type)
{
// Create using 'IntPtr' constructor
MethodInfo? ctor = type.GetMethod("__FactoryNew",
System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Static,
null, new[] { typeof(IntPtr) }, null
);
return ctor;
return type.GetMethods(
System.Reflection.BindingFlags.Static
| System.Reflection.BindingFlags.DeclaredOnly
| System.Reflection.BindingFlags.NonPublic
).FirstOrDefault(x => x.GetCustomAttribute<ConstructAttribute>() is { });
}

private static ConstructorInfo? GetBoxedConstructor(System.Type type)
Expand Down
5 changes: 3 additions & 2 deletions Libs/Gdk-3.0/Records/Event.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ namespace Gdk
{
public partial class Event
{
//TODO: This method is our "secret factory method". it gets called via reflection.
//See BoxedWrapper.cs
// TODO: Workaround as long as we need GDK3 or
// do not create instances from safe handles
[GObject.Construct]
private static Event __FactoryNew(IntPtr ptr)
{
var ev = Marshal.PtrToStructure<Native.EventAny.Struct>(ptr);
Expand Down

0 comments on commit d73171b

Please sign in to comment.