Domanda

I don't know if this is possible or not, but is there a way to call the main function of a .c file using a .java file using JNI (Java Native Interface)? For example

Pseudocode:

/*This is the .c file*/
int main(int argc, char* argv[]){

    File pFile;
    pFile = fopen(argv[1],"r"]);
    fclose(argv[1]);
}

Psuedocode again:

/*This is the .java file*/

public class maincpy{

    static
    {
        System.loadLibrary("maincpy");
    }

    public native int maincpy(int argc, char* argv[]); //

    public static void main(String[] args){
        maincpy c = new maincpy();
        c.main(2,"somefile.txt");
    }
}

I know what I've written is incorrect, because I get errors for using char* argv[] as an argument for the native function. But I hope this gets the idea across for what I am trying to do. Any help would be appreciated.

È stato utile?

Soluzione

It it possible to ultimately call a native main() function, but not afaik possible to do so directly from Java, for two reasons:

1) JNI functions must conform to a specific naming scheme which encodes where they fall in the Java package/class hierarchy

2) JNI functions can only have specific java-compatible data types as arguments and return values

Your solution would be to make a JNI compatible function with JNI compatible arguments and return type, which converts the arguments and calls through to the ordinary native main() function from within its body.

You also need to consider if what the main() function does will be compatible with the jvm. If main() simply does some work and then returns it probably will be. But if it might end up calling exit() that will end the process hosting the jvm. And if main does not return soon, you may need to do this all from a thread, either created on the java side before the JNI call, or created on the native side in the JNI compatible function, and have the thread it starts call main().

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top