代码之家  ›  专栏  ›  技术社区  ›  codeboxes

as3commons在运行时生成函数调用

  •  1
  • codeboxes  · 技术社区  · 9 年前

    出于某些原因,我在运行时生成了一个类,该类有一个现有的超类和一个受保护的成员,并实现了一个现有接口。接口的每个方法(和访问器)也需要生成。我要强调的是用正确的操作码填充方法体。 下面是一个我想生成或转换为操作码的示例:

    public function myFunction(arg1:String, arg2:int):Boolean
    {
        return member.my_namespace::myFunction(arg1, arg2);
    }
    

    所有信息都可用,如函数名、参数、返回类型和命名空间。我能够创建函数本身并返回默认值,如 as3commons tests/examples

    也许我应该使用另一个库而不是as3commons?

    1 回复  |  直到 9 年前
        1
  •  0
  •   codeboxes    9 年前

    我自己找到了答案。我所缺少的只是(正确)使用QualifiedName来访问成员及其功能。我只删除了名称空间。这就是我在模板代码中修改的所有内容:

    public function myFunction(arg1:String, arg2:int):Boolean
    {
        return member.myFunction(arg1, arg2);
    }
    

    下面是生成该函数所需的源代码,包括方法体的Opcode:

    var abcBuilder:AbcBuilder = new AbcBuilder();
    
    //build the class with the super class and the interface
    var packageBuilder:IPackageBuilder = abcBuilder.definePackage("my.package");
    var classBuilder:IClassBuilder = packageBuilder.defineClass("RuntimeClass", "my.package.BaseClass");
    classBuilder.implementInterface("my.package.IMyInterface");
    
    //build the function
    var methodBuilder:IMethodBuilder = classBuilder.defineMethod("myFunction");
    methodBuilder.returnType = "Boolean";
    methodBuilder.visibility = MemberVisibility.PUBLIC;
    methodBuilder.isFinal = true;
    
    //add the parameters
    methodBuilder.defineArgument("String");
    methodBuilder.defineArgument("int");
    
    //here begins the method body with the opcode
    methodBuilder.addOpcode(Opcode.getlocal_0);
    methodBuilder.addOpcode(Opcode.pushscope);
    //call the member "member"
    methodBuilder.addOpcode(Opcode.getlex, [new QualifiedName("member", LNamespace.PUBLIC)]);
    //access to the function args
    methodBuilder.addOpcode(Opcode.getlocal_1);
    methodBuilder.addOpcode(Opcode.getlocal_2);
    //call the function at the above prepared member with the prepared args
    methodBuilder.addOpcode(Opcode.callproperty, [new QualifiedName("myFunction", LNamespace.PUBLIC), 2]);
    //return the result
    methodBuilder.addOpcode(Opcode.returnvalue);
    
    //fire at own will
    abcBuilder.addEventListener(Event.COMPLETE, loadedHandler);
    abcBuilder.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
    abcBuilder.addEventListener(IOErrorEvent.VERIFY_ERROR, errorHandler);
    abcBuilder.buildAndLoad();
    

    我不能保证代码能正常工作。我在自己的项目中用一些动态的东西和循环对它进行了调整,在那里它工作得很好。 我使用的库(d)是:

    • 作为3个常用字节-1.1.1
    • as3共有-0.3.7
    • as3常见缺陷-2.7
    • as3常见问题-1.6.4

    所有可在 as3commons downloads