Jasmin invoke a method using arguments

孤街浪徒 提交于 2019-12-13 08:01:27

问题


I'm writing a compiler that generates Jasmin code and I want to invoke a method using an argument, as follows:

val test(val x) {
    return x;
}

val main (string[] args) {
    test(1);
}

This compiles to:

.class public helloworld
.super java/lang/Object

.method public <init>()V
aload_0
invokenonvirtual java/lang/Object/<init>()V
return
.end method

.method public test(I)I
.limit stack 4
.limit locals 3
iload 1
ireturn
.end method

.method public static main([Ljava/lang/String;)V
.limit stack 4
.limit locals 3
aload_0
ldc 1
invokevirtual helloworld/test(I)I
return
.end method

However, this results in the following error. What am I doing wrong here?

java.lang.VerifyError: (class: helloworld, method: main signature: ([Ljava/lang/String;)V) Incompatible object argument for function call

回答1:


To begin with, the code you 'compile' is not Java, and I'm not sure what it is (pseudo-code?).

The problem with your jasmin code is that it seems you want to call test() as an instance method of the array, which it isn't, because its an instance method of helloworld, which you don't instantiate.

So either you should instantiate the class helloworld, or make test() a static method, so that it can be called without creating an object.

When fixing the jasmin code I also ran into another error: iload 1 should be iload 0. (Programmers like to start counting at 0).

In this code I assume you meant test() to be static.

.class public helloworld
.super java/lang/Object

.method public <init>()V
aload_0
invokenonvirtual java/lang/Object/<init>()V
return
.end method

.method public static test([Ljava/lang/String;)[Ljava/lang/String;
.limit stack 4
.limit locals 3
aload 0
areturn
.end method

.method public static main([Ljava/lang/String;)V
.limit stack 4
.limit locals 3
ldc 1
anewarray java/lang/String
astore 2
aload 2
ldc 0
ldc "bar"
aastore
aload_0
aload 2
invokestatic helloworld/test([Ljava/lang/String;)[Ljava/lang/String;
return
.end method


来源:https://stackoverflow.com/questions/24722634/jasmin-invoke-a-method-using-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!