Beakie
Beakie

Reputation: 2009

Which JNI data type?

I have written some code which passes values between java and c using jni.

Currently all numerics are defined as int (java) -> jnit (jni/c) -> unsigned int (c)

The code works but it is REALLY inefficient because not all the numbers being pass need the memory available to an integer.

I have 3 types of values in my code which need to hold number ranges 0 to 4294967295, 0 to 255 and 0 to 1.

I can't work out compatible data types across all 3 "languages".

Range           Java          C/JNI          C
4294967296      int           jint           unsigned int
256             ???           ???            unsigned char
2               boolean       jboolean       ???

Can you please advise what data types I need to use for the ???s above?

Thanks G

Upvotes: 2

Views: 1084

Answers (2)

default_avatar
default_avatar

Reputation: 303

As for boolean in C there is an answer on this site

and a range of 256 would be covered by byte in java however they are signed so it may prove simpler to use shorts. Essentially the java types are signed and the easiest way to deal with that is to make sure the type your mapping to is larger than the range you want to include so short for a range of 256 and long for 4.2x10^9 as int covers -2,147,483,648 and a maximum value of 2,147,483,647.

Upvotes: 1

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

Remember, there are no unsigned types in Java. So a Java int is not actually going to be able to store all the values of a C unsigned int. You're also operating on the assumption that a C unsigned int is always 32 bits wide. It can be a different size, though the industry has somewhat standardized on it.

With that out of the way, following the logic you have here, int is to jint is to unsigned int as byte is to jbyte is to unsigned char, and as boolean is to jboolean is to _Bool (an underused C99 type that can only hold 1 or 0 as a value.)

Note that a char in C is not the same as a char in Java; the former represents a single byte, however many bits wide it may be, while the latter represents a UTF-16 character. Also note that a char may be signed or unsigned in C depending on the compiler and platform, so to be safe you should explicitly use signed char if the sign might matter.

Upvotes: 1

Related Questions