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