简体   繁体   中英

How to make a JNI for a Java Interface?

How can I make a JNI for a Java Interface so that I can call a function from the interface in c++ code?

Specifically, I have a Java interface

public interface Foo {
    public void Bar(int a);
}

which I attempted to create a JNI for
JFoo.h:

class JFoo {
    ...
    public: 
        void Bar(int a);
    ...
};

JFoo.c:

...
void JFoo::Bar(int a) {
    //Not sure what to put here. If I don't have then I have issues because 
    "declaration of 'void JFoo::Bar(int)' outside of class is not 
    definition"
    return;
} 
...

So from another C++ file I can do

JFoo foo123;
foo123 = ... //the Java object which implements the Foo interface is what actually passes in 'foo123'
foo123.bar(5); //This ideally executes the Java object's implementation of bar

I also tried to use virtual void in JFoo instead to have an abstract c++ class, but that doesn't work because you "cannot declare field 'foo123' to be of abstract type".

How can I make the JNI for the Java interface?

JNI is for implementing instance (without static ) or class ( static ) methods. A method implementation implies a concrete method even if the class contains other methods that are abstract. An interface's methods are entirely abstract.

The language documentation indicates that native is a permissible modifier for a method in a class declaration but does not for an interface declaration . The compiler will also tell you where you can't put native .

Well, it doesn't work like that :(

You can't go like this. JNI allows you to call native methods and manipulate Java objects via functions provided in JNI implementation. But it has nothing to do with one to one mapping.

Take a look here:

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo025

This sample shows how to call method of class from C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM