简体   繁体   中英

Can a Java class implement a C++ interface

Is it possible to a Java class to implement a C++ interface (interface meaning a full abstract class)? Where can I read more about?

Yes, you have to use JNI .

Here's a tutorial from Sun / Oracle

Not directly, no. However, you can create a C++ implementation of that interface that simply delegates to a Java implementation via JNI. See the JNI Specification for more details.

Not in the general sense, no. C++ classes do not exist in the compiled binary the vast majority of the time.

Besides JNI there's another technology named JNA . It seems to be simpler (no need to create C/C++ stub code).

Support for overriding virtual C++ methods is planned in BridJ (a JNA alternative that supports C++), but it's not there yet.

Update: As of version 0.4 , BridJ supports implementing C++ interfaces from Java :

Consider the following C++ class :

#ifndef TEST_EXPORTS
#define TEST_EXPORTS
#endif
class TEST_EXPORTS TestClass {
public:
    virtual int add(int a, int b);
};

You'd bind this class from Java with these BridJ bindings :

public class TestClass extends CPPObject { 
    @Virtual(0) 
    public native int add(int a, int b); 
}; 

And would be able to subclass your C++ class from Java very naturally :

TestClass test = new TestClass() { 
    @Override 
    public int add(int a, int b) { 
        return a + b; 
    } 
}; 

Java class can implement Java interface. Java/C++ communication is done using JNI.

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