When I posted A litte JNI there were several details I glossed over. One important point: the sample code leaks memory. Why? When you call FindClass, the pointer that the JNI returns needs freeing later on. Rather than deal with such a mundane task directly, I actually wrote a small helper template class and specialized it for jclass:
template<>
struct local<jclass>
{
JNIEnv* env;
jclass clazz;
inline local(JNIEnv* env, const char* name) throw()
: env(env), clazz(env->FindClass(name))
{ }
inline ~local() throw()
{ if (clazz) env->DeleteLocalRef(clazz); }
inline operator jclass() const throw() { return clazz; }
#warning Implement the safe bool idiom
operator bool() const { return clazz; }
}; There is still one nit: since there is definitely a sense of "validity" for this class (did FindClass find anything?), I should implemnt the Safe Bool Idiom instead of blindly providing operator bool(). But, as they say, I leave that as an exercise for the reader.
No comments:
Post a Comment