Link to home
Start Free TrialLog in
Avatar of pigpig
pigpig

asked on

JNI: Access a class declared in C++

Dear all,

I have a class declared in C++ and I want to access it in Java code. The problem is I need several instances of the class, so I can't make a global reference to it.

Is there any method that I can pass a pointer of C++ to the Java code? And I need to do something with the class in Java code.

Thank you.

pigpig
Avatar of Igor Bazarny
Igor Bazarny
Flag of Switzerland image

Hi,

You need to write JNI wrapper for your C++ class. Usually C++ pointer fits into java int, so your java class would look like:

class JavaWrapper{
    private int cppClass;
    public JavaWrapper(){
        init();
    }
    public native void doSomething();
    private native void init();
}

On JNI side, create instance of C++ class in init() implementation and store it in the cppClass field. In other methods you can get cppClass fiels and cast it back to C++ pointer type.

Possibly you will need to take care of memory issues--and it's non-trivial. In java, you know when you need new instance, but don't know when you don't need it anymore. You can use finalize() or weak references to clean up your C++ memory.

Regards,
Igor Bazarny,
Brainbench MVP for Java 1
 
Avatar of pigpig
pigpig

ASKER

Hello bazarny,

Do you have some sample codes in doing the pointer conversion in C++? I have some trouble in it.

thx
pigpig

What kind of problem do you have? Is it access to java field or pure C++ problem? I think you just need to cast pointer to long and set value to java field. When you need it back, cast long to same pointer type (unless you are very strict about inheritance/virtual functions use, numeric values of different pointer types pointing to tha same instance may differ)

Regards,
Igor Bazarny


Avatar of pigpig

ASKER

Can u see my problem?
I have a piece of code like that in C++:

#include <iostream.h>

class A
{
public:
     A(int n) : no(n) {}
     int no;
};

void main()
{
     A *a = new A(9);
     
     int apt = (int) &a;

        A *b = (A *)&apt;
        cout << b->no << endl;

     delete a;
}
ASKER CERTIFIED SOLUTION
Avatar of Igor Bazarny
Igor Bazarny
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pigpig

ASKER

done !!!!!!!!
thx very much~~~~~~