We help IT Professionals succeed at work.

Convert C uint8_t pointer to Java representation using JNI

cgray1223
cgray1223 asked
on
Hello,

I have a C function that returns a pointer to a uint8_t (1 byte unsigned integer).  I'm attempting to wrap this function using SWIG/JNI but I would like to cast the actual pointer to the uint8_t.  The JNI pointer is a long.  The below code is from the SWIG interface file.  The void2int8 method does not return the proper value, so I believe the cast is wrong.  The void2str method does work , so I added it here just for reference even though its a separate data type.

long cPtr = $jnicall;
Object oInt = void2int8(cPtr);
Object oStr = void2str(cPtr);

uint8_t void2int8(jlong v) {
  return (uint8_t)v;
} 

const char* void2str(jlong v) {
  return (const char*)v;
}

Open in new window

Comment
Watch Question

Top Expert 2009
Commented:
Since jlong is the pointer value, you need to cast it to a uint8_t* (note the *). If you then want to get the uint8_t value that that pointer points to, you need to dereference that pointer :
uint8_t void2int8(jlong v) {
  return *((uint8_t*) v);
} 

Open in new window


However, it seems far more likely that the pointer points to more than one uint8_t value (ie. a whole array), in which case, you'll have to stick with a uint8_t* :
uint8_t* void2int8(jlong v) {
  return (uint8_t*) v;
} 

Open in new window

Commented:
The answer Infinity08 provides does appear to be correct.
My response here is more curousity than an answer in itself.

How does that uint8_t*   value end up stored in a jlong in the first place if, as you say, it is returned from a C function?

Perhaps the original posted code has a typographic error?
long cPtr = $jnicall;
should this be
jlong cPtr = $jnicall;  and $jnicall is the "C" function being called?

Commented:
So is that C code calling non-C code which then calls C code again?
or have I got this completely wrong?
Top Expert 2009

Commented:
>> So is that C code calling non-C code which then calls C code again?

Yes, that's pretty much what JNI does : http://en.wikipedia.org/wiki/Java_Native_Interface
JNI allows C code to call Java code, and vice versa.

In this case, the jlong value seems to be returned from the Java code (that doesn't really have a concept of pointers), which the C code then has to interpret as a pointer. This assumes that the jlong value was originally passed in to the Java code as a valid pointer from the C code.

Author

Commented:
Thanks Infinity08, your first solution worked (dereferencing the pointer) as it just pointed to one uint_8t value (one byte).