I have been fooling around with CNI in order to interpolate Java and C++ code for the last few hours.
While I was looking the possibility to use the Java collections as a replacement for my old team missing libstd
, I tried to create a java.util.Stack
object and manipulate it.
However, the compiler (gcc
and gcj
, in that probably the same) seems to play his cheap tricks upon my innocent mind:
# gcc -g -I. test.cc
test.cc: In function ‘int main(int, char**)’:
test.cc:24:3: error: ‘java::util::Stack’ is not a template
Stack<Person> *stack = new Stack<Person>();
^
test.cc:24:30: error: ‘java::util::Stack’ is not a template
Stack<Person> *stack = new Stack<Person>();
(the Person object is well defined java class)
Only when I removed the type argument specification, It let me use the data-structure, as if the type argument was chosen to bejava.lang.Object
. The CNI docs seems to mention nothing about it at all! no words about templates indeed.
Does anyone know about using templates in CNI context? is it supported? I searched google
and stackoverflow
for answers, but couldn't come with the slightest clue. Any help will be appreciated.
In addition, I would like to know if i'm using a gcc 2.95.2 (is there a gcj for that gcc version?)
I am working on Virtual Boxed
Ubunto 12
over windows 10
host.
More importantly gcj
and gcc
versions stands on 4.8.4
java --version
yields 1.5
and libgcj 4.8.4
Not a CNI user, but the reason for this one seems to be obvious enough.
Generic specification java.util.Stack<T>
in Java is only a compile time constraint that checks that you add objects of type compatible with T. Internally, java.util.Stack
has only single implementation which accepts all types of Object
s (actually, references to all types of objects). You may even trick compiler into addding not an instance of T by using unsafe conversions. So, java.util.Stack<String>
and java.util.Stack<Date>
are the same internally.
C++ is different. Instantiation of the same template with different arguments creates different incompatible types. For example, std::stack<int>
, std::stack<int*>
and std::stack<char>
are totally different implementations and have different code. C++ template mechanism is a superset of java generics.
If, for example, you wanted to get Java functionality in C++, you would write std::stack<void*>
even if you wanted to store objects of some particular type T. Type conversion to T has to be done manually.
CNI does the same thing. It instantiates the only one implementation of java.util.Stack
which can accept all types of objects.