Erweiterung für BRL.Reflection

Übersicht BlitzMax, BlitzMax NG Codearchiv & Module

Neue Antwort erstellen

BtbN

Betreff: Erweiterung für BRL.Reflection

BeitragMo, Apr 27, 2009 18:08
Antworten mit Zitat
Benutzer-Profile anzeigen
Da ich dies kürzlich für ein paar Python-Basteleien brauchte, hier ein Weg, funktionen eines Types per reflection aufzurufen:

Code: [AUSKLAPPEN]
Type TFunction
   Field name:String
   Field fptr:Byte Ptr
   Field params:String
EndType

Function RefrGetFunctions:TFunction[](tt:TTypeId)
   If Not tt._class Return Null

   Local debug:Int=(Int Ptr tt._class)[2]
   Local p:Int Ptr=(Int Ptr debug)+2
   Local ret:TFunction[0]
   
   While p[0]
      Local id:String=String.FromCString( Byte Ptr p[1] )
      Local ty:String=String.FromCString( Byte Ptr p[2] )
      
      Local meta:String
      Local i:Int=ty.Find( "{" )
      If i<>-1
         meta=ty[i+1..ty.length-1]
         ty=ty[..i]
      EndIf

      Select p[0]
         Case 7
            ret = ret[..ret.length+1]
            Local n:TFunction = New TFunction
            n.name = id
            n.params = ty
            n.fptr = Byte Ptr(Int Ptr(tt._class + p[3])[0])
            ret[ret.length-1] = n
      End Select
      p:+4
   Wend

   Return ret
EndFunction

Function RefrGetFuncPtr:Byte Ptr(tt:TTypeId, name:String)
   If Not tt._class Return Null
   name = name.toLower()

   Local debug:Int=(Int Ptr tt._class)[2]
   Local p:Int Ptr=(Int Ptr debug)+2
   
   While p[0]
      Local id:String=String.FromCString( Byte Ptr p[1] )
      Local ty:String=String.FromCString( Byte Ptr p[2] )
      
      Local meta:String
      Local i:Int=ty.Find( "{" )
      If i<>-1
         meta=ty[i+1..ty.length-1]
         ty=ty[..i]
      EndIf

      Select p[0]
         Case 7
            If id.ToLower() = name Then
               Return Byte Ptr(Int Ptr(tt._class + p[3])[0])
            EndIf
      End Select
      p:+4
   Wend

   Return Null
EndFunction



Hier noch ein kleines Beispiel:

Code: [AUSKLAPPEN]
Type TTestType
   Function DoSomething(n:String)
      Print n
   EndFunction

   Function DoSomethingOther:Int(a:Int, b:Int)
      Return a+b
   EndFunction
EndType

Global t:TTypeId = TTypeId.ForName("TTestType")

For Local f:TFunction = EachIn RefrGetFunctions(t)
   Print f.name
   Print f.params
Next

Global f1(n:String) = RefrGetFuncPtr(t, "DoSomething")
Global f2:Int(a:Int, b:Int) = RefrGetFuncPtr(t, "DoSomethingOther")

f1("Hello You!")
Print f2(2,3)

End

Neue Antwort erstellen


Übersicht BlitzMax, BlitzMax NG Codearchiv & Module

Gehe zu:

Powered by phpBB © 2001 - 2006, phpBB Group