2

I want to call the Java bindings of my C++ class like that :

std::streamsize DataStreamJava::length() const {
  jmethodID m = jni()->GetMethodID(j_dataStream_class_,
                                   "length", "()J");
  return jni()->CallLongMethod(j_dataStream_global_, m);
}

But it is not possible since these JNI calls are not const.

Does JNI provide const functions for const methods ? Is removing const attributes the only way to solve this problem ?

Axel Isouard
  • 1,498
  • 1
  • 24
  • 38
  • 1
    Do you have a `const JNIEnv*` for some reason? Why? – Tavian Barnes Oct 20 '15 at 18:44
  • 1
    To expand on @TavianBarnes' comment: you can keep a pointer to `JNIEnv` in your object, but you have no control on the `JNIEnv`, it does not belong to your object or class. Therefore it is perfectly legitimate to declare it as **mutable**. – Alex Cohn Oct 21 '15 at 09:22

3 Answers3

3

I think the short answer is "no." There's no const version of these JNI functions. The next question maybe is "Should there be?" I think that the answer to that is also "no." JNI functions all potentially change the state of the JVM. (At minimum they all have the capability to create an error in the JVM, which changes its internal state.) I think that actually violates the contract implied by your const attribute - It's not just some design flaw in the JNI header files.

Brick
  • 3,998
  • 8
  • 27
  • 47
1

JNI apart, you want to invoke a non-const method inside a const one.

I think you can do it using a const_cast<>, but read the details first.

Community
  • 1
  • 1
bonnyz
  • 13,458
  • 5
  • 46
  • 70
1

If JNI doesn't have the const annotations you want, this may be a case where mutable might actually be a good idea. Tag the JNI members as mutable and check logical const-ness by hand.

dspeyer
  • 2,904
  • 1
  • 18
  • 24