2

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

Beakie
  • 1,948
  • 3
  • 20
  • 46
  • On some architectures (notably ARM) working with 32-bit values is faster than with 16/8 bit ones. So unless it's storage space we're talking about, passing parameters as `int`/`jint` might be a net win. – Seva Alekseyev Oct 29 '11 at 16:26

2 Answers2

1

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.

Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
1

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.

Community
  • 1
  • 1
default_avatar
  • 306
  • 3
  • 14
  • unsigned char *body = (*env)->GetShortArrayElements(env, myjshortArray, 0); I get a "warning: initialization from incompatible pointer type" – Beakie Oct 29 '11 at 17:00