Next: , Previous: Strings, Up: About CNI


10.11 Interoperating with C/C++

Because CNI is designed to represent Java classes and methods it cannot be mixed readily with C/C++ types.

One important restriction is that Java classes cannot have non-Java type instance or static variables and cannot have methods which take non-Java types as arguments or return non-Java types.

None of the following is possible with CNI:

     
     class ::MyClass : public java::lang::Object
     {
        char* variable;  // char* is not a valid Java type.
     }
     
     
     uint
     ::SomeClass::someMethod (char *arg)
     {
       .
       .
       .
     }   // uint is not a valid Java type, neither is char*

Of course, it is ok to use C/C++ types within the scope of a method:

     jint
     ::SomeClass::otherMethod (jstring str)
     {
        char *arg = ...
        .
        .
        .
     }

But this restriction can cause a problem so CNI includes the gnu.gcj.RawData class. The RawData class is a non-scanned reference type. In other words variables declared of type RawData can contain any data and are not checked by the compiler in any way.

This means that you can put C/C++ data structures (including classes) in your CNI classes, as long as you use the appropriate cast.

Here are some examples:

     
     class ::MyClass : public java::lang::Object
     {
        gnu.gcj.RawData string;
     
        MyClass ();
        gnu.gcj.RawData getText ();
        void printText ();
     }
     
     ::MyClass::MyClass ()
     {
        char* text = ...
        string = text;
     }
     
     gnu.gcj.RawData
     ::MyClass::getText ()
     {
        return string;
     }
     
     void
     ::MyClass::printText ()
     {
       printf("%s\n", (char*) string);
     }