We help IT Professionals succeed at work.

JNI - Passing (void*) from C/C++

slinky
slinky asked
on
Medium Priority
1,437 Views
Last Modified: 2012-05-05
I am using a C API which I want to call from Java using JNI. I have this working but there is one thing I'd like to change.

The C returns a handle which is essentially a void*

Many of the subsequent C API calls require the void* to be passed into it e.g.

void* a;
a = call1();
call2(a, "stuff");

What I'd like to do is make call1 and call2 from Java but this will require that I transfer the void* to java and pass it back into call2.

After a run through all the JNI stuff I could find I couldn't find a way of doing this. It might not be possible but I'm sure someone here can tell me definitively!

Thanks in advance.
Comment
Watch Question

Commented:
One option is to declare a long variable in your java class and use it to store your C++ void * pointer.

Use JNI's SetLongField and GetLongField to store and retrieve the data.

You will need to cast the void * to a jlong in your JNI/C++ code.

Author

Commented:
Seems like a plan, I'll give it a go!

Commented:
doogzr,

do u have the details of how to do it?

pigpig

Author

Commented:
You don't need to use SetLongField (as I remember, it was a while back).

In the Java I had a long
In the C, I took the pointer and cast it to a jlong and returned it. I could then pass it back into the C as a jlong and cast it back to a void* in the C.

It all worked fine.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.