How to implement a java interface in c++?
Michael Koch
konqueror@gmx.de
Thu May 18 09:44:00 GMT 2006
On Thu, May 18, 2006 at 11:06:36AM +0200, mirleau@bluewin.ch wrote:
> >The only way I see for you is the subclass in java code
> >and impement all methods of that class in C++. Thats easily possible
> >with CNI. And it should be fast.
> >
> >
> >Michael
>> Hi, thanks for your suggestion, I'd like to try it, but I'm not
> expert enough to do what I think you meant. Here's what I did:
>> I wrote a java subclass:
> ====CppImplementation.java========================
> public class CppImplementation implements JavaInterface
> {
> public void doIt(){int a = 1;}
> }
> =====================================
>> And used gcjh to generate a header file:
>> ====CppImplementation.h=================================
> // DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
>> #ifndef __CppImplementation__
> #define __CppImplementation__
>> #pragma interface
>> #include <java/lang/Object.h>
>> extern "Java"
> {
> class CppImplementation;
> };
>> class ::CppImplementation : public ::java::lang::Object
> {
> public:
> virtual void doIt ();
> CppImplementation ();
>> static ::java::lang::Class class$;
> };
>> #endif /* __CppImplementation__ */
>>> ==============================================
>> The way I interpret your answer is that I could now forget the
> java class and just directly implement this header file in c++.
>> I'm not certain on how to do that. I guess I need to use
> gcj conventions to correctly implement it.
>> For example I was playing around by in-/out commenting some lines
> below, but that didn't work out link-wise: (vtables and Object::Object()):
> ============ CppImplementation.cc =================
> #include "CppImplementation.h" // generated by gcjh
>> // #pragma interface
>> #include <java/lang/Object.h>
>> //extern "Java"
> //{
> // class CppImplementation;
> //};
>> void CppImplementation::doIt (){};
> CppImplementation::CppImplementation (){};
> ::java::lang::Class CppImplementation::class$;
>> ===================================================
No. Just add the "native" keyword to your methods in the java class like
this:
====CppImplementation.java========================
public class CppImplementation implements JavaInterface
{
public native void doIt():
}
=====================================
Then you add a *.cpp file containing a normal C++ method implementation:
#include "CppImplementation.h"
void
CppImplementation::doIt()
{
// Do something
}
The needed header file can be generated with gcjh.
Michael
--
Escape the Java Trap with GNU Classpath!
http://www.gnu.org/philosophy/java-trap.html
Join the community at http://planet.classpath.org/
More information about the Java
mailing list