jni_int_wrapper.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_ANDROID_JNI_INT_WRAPPER_H_
  5. #define BASE_ANDROID_JNI_INT_WRAPPER_H_
  6. // Wrapper used to receive int when calling Java from native.
  7. // The wrapper disallows automatic conversion of long to int.
  8. // This is to avoid a common anti-pattern where a Java int is used
  9. // to receive a native pointer. Please use a Java long to receive
  10. // native pointers, so that the code works on both 32-bit and 64-bit
  11. // platforms. Note the wrapper allows other lossy conversions into
  12. // jint that could be consider anti-patterns, such as from size_t.
  13. // Checking is only done in debugging builds.
  14. #ifdef NDEBUG
  15. typedef jint JniIntWrapper;
  16. // This inline is sufficiently trivial that it does not change the
  17. // final code generated by g++.
  18. inline jint as_jint(JniIntWrapper wrapper) {
  19. return wrapper;
  20. }
  21. #else
  22. class JniIntWrapper {
  23. public:
  24. JniIntWrapper() : i_(0) {}
  25. JniIntWrapper(int i) : i_(i) {}
  26. JniIntWrapper(const JniIntWrapper& ji) : i_(ji.i_) {}
  27. template <class T> JniIntWrapper(const T& t) : i_(t) {}
  28. jint as_jint() const { return i_; }
  29. private:
  30. // If you get an "is private" error at the line below it is because you used
  31. // an implicit conversion to convert a long to an int when calling Java.
  32. // We disallow this, as a common anti-pattern allows converting a native
  33. // pointer (intptr_t) to a Java int. Please use a Java long to represent
  34. // a native pointer. If you want a lossy conversion, please use an
  35. // explicit conversion in your C++ code. Note an error is only seen when
  36. // compiling on a 64-bit platform, as intptr_t is indistinguishable from
  37. // int on 32-bit platforms.
  38. JniIntWrapper(long);
  39. jint i_;
  40. };
  41. inline jint as_jint(const JniIntWrapper& wrapper) {
  42. return wrapper.as_jint();
  43. }
  44. #endif // NDEBUG
  45. #endif // BASE_ANDROID_JNI_INT_WRAPPER_H_