aspose file tools*
The moose likes Other JSE/JEE APIs and the fly likes create c++ object from java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Other JSE/JEE APIs
Bookmark "create c++ object from java" Watch "create c++ object from java" New topic
Author

create c++ object from java

Abdul Basit
Greenhorn

Joined: Jan 25, 2002
Posts: 27
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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?


[Jess in Action][AskingGoodQuestions]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: create c++ object from java