bindings.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #ifndef BINDINGS_H_
  19. #define BINDINGS_H_
  20. #include "libhdfs++/status.h"
  21. #include "common/util.h"
  22. #include <google/protobuf/message_lite.h>
  23. #include <jni.h>
  24. namespace hdfs {
  25. class StatusHelper {
  26. public:
  27. static std::pair<const char *, size_t> Rep(const Status &status) {
  28. const char *state = status.state_;
  29. size_t length = *reinterpret_cast<const uint32_t*>(state);
  30. return std::make_pair(state, length + 8);
  31. }
  32. };
  33. }
  34. static inline jbyteArray ToJavaStatusRep(JNIEnv *env, const hdfs::Status &stat) {
  35. if (stat.ok()) {
  36. return nullptr;
  37. }
  38. auto rep = hdfs::StatusHelper::Rep(stat);
  39. jbyteArray arr = env->NewByteArray(rep.second);
  40. void *b = env->GetPrimitiveArrayCritical(arr, nullptr);
  41. memcpy(b, rep.first, rep.second);
  42. env->ReleasePrimitiveArrayCritical(arr, b, 0);
  43. return arr;
  44. }
  45. static inline void SetStatusArray(JNIEnv *env, jobjectArray jstatus, const hdfs::Status &stat) {
  46. jbyteArray arr = ToJavaStatusRep(env, stat);
  47. env->SetObjectArrayElement(jstatus, 0, arr);
  48. }
  49. static inline void ReadPBMessage(JNIEnv *env, jbyteArray jbytes, ::google::protobuf::MessageLite *msg) {
  50. void *b = env->GetPrimitiveArrayCritical(jbytes, nullptr);
  51. msg->ParseFromArray(b, env->GetArrayLength(jbytes));
  52. env->ReleasePrimitiveArrayCritical(jbytes, b, JNI_ABORT);
  53. }
  54. static inline std::string ReadByteString(JNIEnv *env, jbyteArray jbytes) {
  55. char *data = reinterpret_cast<char*>(env->GetPrimitiveArrayCritical(jbytes, nullptr));
  56. std::string res(data, env->GetArrayLength(jbytes));
  57. env->ReleasePrimitiveArrayCritical(jbytes, data, JNI_ABORT);
  58. return res;
  59. }
  60. #endif