1 /******************************************************************
3 * Copyright 2015 Samsung Electronics All Rights Reserved.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 ******************************************************************/
21 #ifndef JNI_RCS_OBJECT_H_
22 #define JNI_RCS_OBJECT_H_
28 #include "JavaClasses.h"
29 #include "JNIEnvWrapper.h"
31 extern jfieldID g_field_mNativeHandle;
33 void initRCSObject(JNIEnvWrapper*);
34 void clearRCSObject(JNIEnvWrapper*);
38 struct BaseHandleHolder
40 virtual ~BaseHandleHolder() {}
43 template< typename T >
44 struct HandleHolder: public BaseHandleHolder
46 HandleHolder(T* ptr) : m_ptr { ptr } {}
48 virtual ~HandleHolder() { delete m_ptr; }
53 template< typename ENV >
54 void* getNativeHandle(ENV* env, jobject obj)
56 return reinterpret_cast< void* >(env->GetLongField(obj, g_field_mNativeHandle));
60 template< typename ENV >
61 bool hasNativeHandle(ENV* env, jobject obj)
63 return Detail::getNativeHandle(env, obj) != nullptr;
66 template< typename T, typename ENV, typename ...PARAMS >
67 inline void setSafeNativeHandle(ENV* env, jobject obj, PARAMS&&... params)
69 static_assert(!std::is_array< T >::value, "Array is not supported!");
71 std::unique_ptr< Detail::HandleHolder< T > > p(
72 new Detail::HandleHolder< T >{ new T{ std::forward< PARAMS >(params)... } });
74 env->SetLongField(obj, g_field_mNativeHandle, reinterpret_cast< jlong >(p.get()));
76 if (env->ExceptionCheck()) return;
81 template< typename ENV >
82 void releaseNativeHandle(ENV* env, jobject obj)
84 auto handleHolder = reinterpret_cast< Detail::BaseHandleHolder* >(
85 env->GetLongField(obj, g_field_mNativeHandle));
89 env->SetLongField(obj, g_field_mNativeHandle, 0);
93 template< typename T >
94 inline T& getNativeHandleAs(JNIEnv* env, jobject obj)
96 auto handleHolder = static_cast< Detail::HandleHolder< T >* >(Detail::getNativeHandle(env, obj));
100 env->ThrowNew(env->FindClass(EXC_NAME_ILLEGAL_STATE), "Internal handle is null!");
103 return *handleHolder->m_ptr;
106 template< typename T >
107 inline T& getNativeHandleAs(JNIEnvWrapper* env, jobject obj)
109 getNativeHandleAs< T >(env->get(), obj);
110 if (env->ExceptionCheck()) throw JavaException();
118 JNIEXPORT void JNICALL
119 Java_org_iotivity_service_RcsObject_nativeDispose(JNIEnv*, jobject);
125 #endif // JNI_RCS_OBJECT_H_