Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

create c++ object from java

 
Abdul Basit
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can i create a C++ class object from java code through JNI, I know how i can call C language methods , but still i not get an example which explain clearly how can we create c++ object in java and then call method from that object.

one post on a forum saying
"In the constructor of your Java object, you'll have to call your 'createObjectOnHeap' function to actually instantiate your C++ object."

u can check this post on below link
http://jguru.com/faq/view.jsp?EID=710841
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The thread you're pointing to is correct if what you want to do is "wrap" a C++ object as a Java object, so that in Java it looks as though you've got an instance of the C++ class to play with.

All he's saying is that you'll need to create native method wrappers for each of the C++ class's methods (or at least, for the ones you want to call) and, in addition, you'll need to write a method to create a C++ object (which the poster called "createObjectOnHeap()") and another one to delete the object (which the poster called "deleteObjectOnHeap()"). There's no magic here.

The one potentially tricky thing, I suppose, is that the Java object will want to keep a reference to the C++ object in between calls. There's no perfect, portable way to do this, as you're going to have to convert a C++ pointer into a Java primitive and back. Most of the time, though, a Java "int" will be fine. So the Java object will need an int member, and createObjectOnHeap() would use "new" to create a C++ object, static_cast to a void*, cast the void* to an int, and return the int. The Java code that called the createObjectOnHeap() method would store the return value in a Java int. Then all the other native method wrappers would accept an int as a parameter, and they would cast the int to a void*, then static_cast to a pointer to your C++ class.

If, on the other hand, you just want to work with a C++ object within a single native method, then there's nothing to it: just do it.

Does this all make sense?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic