Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern "Java" block in GCC

I found an interesting feature in GCC documentation for C++:

java_interface

This type attribute informs C++ that the class is a Java interface. It may only be applied to classes declared within an extern "Java" block. Calls to methods declared in this interface will be dispatched using GCJ's interface table mechanism, instead of regular virtual table dispatch.

As I understand it will look something like this:

extern "Java" {
    class NativeClass __attribute__((java_interface)) {
        //Implementation on native methods goes here.
    }
}

Does anybody know details about this? How to call methods of NativeClass from Java? Maybe anybody tried it in real live?

like image 379
Ihar Avatar asked Mar 01 '13 22:03

Ihar


1 Answers

GCJ provides two native interfaces for Java: JNI using C and CNI using C++. Since the example you quote uses a class, it has to refer to the latter. The CNI documentation on interfaces only describes how to access interfaces described in Java from C++ code. Your example appears to work the other way round: a class written in C++ which is accessible from Java and serves as a Java interface.

But there are pretty few details about this available, so trial and error will be one way to experiment with this, and looking at the actual GCC sources would be another. If you want to see one example of both the extern "Java" block and the java_interface attribute, have a look at java/lang/Readable.h. It contains the C++ representation of the Java interface java.lang.Readable. As the first line of that file states, it is machine generated. So probably the reason why there is so little documentation is because you aren't supposed to write this stuff yourself. It's just a detail of how GCJ implements CNI. And looking more closely at the above file, it seems they even violate their own documentation, since that Readable.h has the attribute outside the extern block, in contrast to the snippet you quoted.

like image 166
MvG Avatar answered Nov 04 '22 23:11

MvG