Merhabalar, C++ Qt projesinde Java kodunu nasıl kullanıyoruz derken sizinde tüyleriniz diken diken oldu mu ?
Bloğumdaki ilk gönderimde bu konuyu seçmemin nedeni;
Kendimi blog yazmaya heveslendirmek için programcılıkta en çok sevdiğim yöntem olan tek bir projeden diğer platformlara has özelliklerin kullanılabilmesini sizinle paylaşmak istiyorum.
Bu işe neden ihtiyaç duyuyoruz ona da değinecek olursak, C++ Qt Framework u üzerinden Android ve ya iOS platformuna ait spesifik özelliklerini kullanabilmesi imkansızdır (Ağ durumu, Rehber, Pil seviyesi, şarj durumu vs.).
Bu yüzdendir ki, 2 platformada aynı hizmeti vermeyi hedefleyen oluşturacağımız temel bir interface ile platformun native (java,obj-c,swift) programlama dili ile oluşturulmuş bir methodu çağırabiliyor veya platform methodundan c++ tarafındaki methodu tetikletebiliyor olmamız gerekiyor.
Java kısmından bahsedecek olursak, Android platformuna ait özellikleri kullanmak üzere onlara erişmek için JNI (Java Native Interface) olarak adlandırılan bir shared object içindeki C/C++ fonksiyonlarının java içinde kullanılmasında köprü vazifesi gören bir teknolojiyi kullanacağız . Elbette JNI teknolojisi sadece C/C++ kodlarının çağrılmasından ibaret değildir. Bunun içine javanın içinde barındırmadığı çağrılar ve alt seviyeli diller (assembler gibi) yardımıyla javanın ulaşamadığı platforma bağlı bir çok native kodlar da girmektedir.
JNI, diğer dillerde yazılmış uygulamaların, native kısmından çağrılacak ve çağrılabilecek bir framework. Çoğunlukla, platforma özgü özelliklere erişme, yüksek performanslı modüller ve java binding i C/C++ ile yazmak için kullanılır
İhtiyac duyduğum qt projelerimde kullanmış olduğum JNI için C++ wrapper sınıfı sizinle paylaşayım.
Öncelikle, C++ wrapper sınıfımızı oluştururken RAII (Resource Acquisition Is Initialization) tekniğini kullanmak çok faydalı olacaktır. (Bir kaynak yaşam döngüsünü (tahsis edilen bellek, yürütme iş parçacığı, açık soket, açık dosya, kilitli mutex, veritabanı bağlantısı-sınırlı kaynağı olan her şeyi) bir nesnenin ömrüne bağlar.)
Bjarne Stroustrup’s C++ Style and Technique FAQ
Bu iki avantaja sahiptir;
- Tam olarak bir C++ nesnesi bir Java nesnesini temsil eder.
- Oluşturulan referansları hafızadan serbest bırakmayı hatırlamak zorunda kalmayız.
JNI’daki referans türlerini incelemek isteyebilirsiniz
JniObject, sınıf ve nesne için global referansları tutacak,
C++ nesnesi yok edilinceye kadar garbage collector tarafından silinmeyecek. (RAII, kaynağın nesneye erişebilecek herhangi bir işlev için kullanılabileceğini garanti eder)
Not: Kendi sabırsızlığım yüzünden yazıyı istemiş gibi tamamlayamadım ama ben göndermek istiyorum. Saat 01:00 olmak üzere, sonrasında kaldığım yerden devam edeceğim.
jniobject.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 |
#ifndef JNIOBJECT_H #define JNIOBJECT_H #include <jni.h> #include <string> #include <sstream> #include <vector> #include <map> #include <array> #include <list> #include <set> #include <cassert> #include <QObject> class Jni{ private: typedef std::map<std::string, jclass> ClassMap; JavaVM* _java; JNIEnv* _env; ClassMap _classes; Jni(); Jni(const Jni& other); public: ~Jni(); /** * This class is a singleton */ static Jni& get(); /** * Set the java virtual machine pointer */ void setJava(JavaVM* java); /** * Get the java virtual machine pointer */ JavaVM* getJava(); /** * Get the java environment pointer * Will attatch to the current thread automatically */ JNIEnv* getEnvironment(); /** * get a class, will be stored in64 the class cache */ jclass getClass(const std::string& classPath, bool cache=true); }; class JniObjectn { private: jclass _class; jobject _instance; std::string _error; std::string _classPath; template<typename Arg, typename... Args> static void buildSignature(std::ostringstream& os, const Arg& arg, const Args&... args){ os << getSignaturePart(arg); buildSignature(os, args...); } static void buildSignature(std::ostringstream& os){ } template<typename Return, typename... Args> static std::string createSignature(const Return& ret, const Args&... args){ std::ostringstream os; os << "("; buildSignature(os, args...); os << ")" << getSignaturePart(ret); return os.str(); } template<typename... Args> static std::string createVoidSignature(const Args&... args){ std::ostringstream os; os << "("; buildSignature(os, args...); os << ")" << getSignaturePart(); return os.str(); } template<typename... Args> static jvalue* createArguments(const Args&... args){ jvalue* jargs = (jvalue*)malloc(sizeof(jvalue)*sizeof...(Args)); buildArguments(jargs, 0, args...); return jargs; } static jvalue* createArguments(){ return nullptr; } template<typename Arg, typename... Args> static jvalue* buildArguments(jvalue* jargs, unsigned pos, const Arg& arg, const Args&... args){ jargs[pos] = convertToJavaValue(arg); buildArguments(jargs, pos+1, args...); } static jvalue* buildArguments(jvalue* jargs, unsigned pos){ } /** * Return the signature for the given type */ template<typename Type> static std::string getSignaturePart(const Type& type); /** * Return the signature for the given container element */ template<typename Type> static std::string getContainerElementSignaturePart(const Type& container){ if(container.empty()){ return getSignaturePart(typename Type::value_type()); }else{ return getSignaturePart(*container.begin()); } } // template specialization for pointers template<typename Type> static std::string getSignaturePart(Type* val){ return getSignaturePart((jlong)val); } // template specialization for containers template<typename Type> static std::string getSignaturePart(const std::vector<Type>& val){ return std::string("[")+getContainerElementSignaturePart(val); } template<typename Type> static std::string getSignaturePart(const std::set<Type>& val){ return std::string("[")+getContainerElementSignaturePart(val); } template<typename Type, int Size> static std::string getSignaturePart(const std::array<Type, Size>& val){ return std::string("[")+getContainerElementSignaturePart(val); } template<typename Type> static std::string getSignaturePart(const std::list<Type>& val){ return std::string("[")+getContainerElementSignaturePart(val); } template<typename Key, typename Value> static std::string getSignaturePart(const std::map<Key, Value>& val){ return "Ljava/util/Map;"; } /** * Return the signature for the void type */ static std::string getSignaturePart(); template<typename Return> Return callStaticJavaMethod(JNIEnv* env, jclass classId, jmethodID methodId, jvalue* args); void callJavaVoidMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args); template<typename Return> void callJavaMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args, Return& out); template<typename Return> void callJavaObjectMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args, Return& out){ jobject jout = nullptr; callJavaMethod(env, objId, methodId, args, jout); out = convertFromJavaObject<Return>(jout); } template<typename Type> void callJavaMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args, std::vector<Type>& out){ callJavaObjectMethod(env, objId, methodId, args, out); } template<typename Return> Return getJavaStaticField(JNIEnv* env, jclass classId, jfieldID fieldId); template<typename Return> Return getJavaField(JNIEnv* env, jobject objId, jfieldID fieldId); void setError(const std::string& msg); public: JniObject(const std::string& classPath, jobject javaObj=nullptr, jclass classId=nullptr); JniObject(jclass classId, jobject javaObj); JniObject(jobject javaObj=nullptr); JniObject(const JniObject& other); void init(jobject javaObj=nullptr, jclass classId=nullptr, const std::string& classPath=""); ~JniObject(); /** * Clear the retained global references */ void clear(); /** * Find a singleton instance * will try the `instance` static field and a `getInstance` static method */ static JniObject findSingleton(const std::string& classPath); /** * Create a new JniObject */ template<typename... Args> static JniObject createNew(const std::string& classPath, Args&&... args){ JniObject defRet(classPath); JNIEnv* env = getEnvironment(); if(!env){ return defRet; } jclass classId = Jni::get().getClass(classPath); if(!classId){ return defRet; } std::string signature(createVoidSignature<Args...>(args...)); jmethodID methodId = env->GetMethodID(classId, "<init>", signature.c_str()); if (!methodId || env->ExceptionCheck()){ env->ExceptionClear(); defRet.setError(std::string("Failed to find constructor '"+classPath+"' with signature '"+signature+"'.")); }else{ jvalue* jargs = createArguments(args...); jobject obj = env->NewObjectA(classId, methodId, jargs); if (env->ExceptionCheck()){ env->ExceptionClear(); defRet.setError(std::string("Failed to call constructor '"+classPath+"' with signature '"+signature+"'.")); }else{ defRet = JniObject(classPath, obj, classId); } } return defRet; } /** * Calls an object method */ template<typename Return, typename... Args> Return call(const std::string& name, const Return& defRet, Args&&... args){ std::string signature(createSignature(defRet, args...)); return callSigned(name, signature, defRet, args...); } template<typename Return, typename... Args> Return callSigned(const std::string& name, const std::string& signature, const Return& defRet, Args&&... args){ JNIEnv* env = getEnvironment(); if(!env){ return defRet; } jclass classId = getClass(); if(!classId){ return defRet; } jobject objId = getInstance(); if(!objId){ return defRet; } jmethodID methodId = env->GetMethodID(classId, name.c_str(), signature.c_str()); if (!methodId || env->ExceptionCheck()){ env->ExceptionClear(); setError(std::string("Failed to find method '")+name+"' with signature '"+signature+"'."); return defRet; }else{ jvalue* jargs = createArguments(args...); Return result; callJavaMethod(env, objId, methodId, jargs, result); if (env->ExceptionCheck()){ env->ExceptionClear(); setError(std::string("Failed to call method '")+name+" with signature '"+signature+"'."); return defRet; }else{ return result; } } } /** * Calls an object void method */ template<typename... Args> void callVoid(const std::string& name, Args&&... args){ std::string signature(createVoidSignature(args...)); return callSignedVoid(name, signature, args...); } template<typename... Args> void callSignedVoid(const std::string& name, const std::string& signature, Args&&... args){ JNIEnv* env = getEnvironment(); if(!env){ return; } jclass classId = getClass(); if(!classId){ setError(std::string("Could not invoke '")+name+"': class not found."); return; } jobject objId = getInstance(); if(!objId){ return; } jmethodID methodId = env->GetMethodID(classId, name.c_str(), signature.c_str()); if (!methodId || env->ExceptionCheck()){ env->ExceptionClear(); setError(std::string("Failed to find method '")+name+"' with signature '"+signature+"'."); }else{ jvalue* jargs = createArguments(args...); callJavaVoidMethod(env, objId, methodId, jargs); if (env->ExceptionCheck()){ env->ExceptionClear(); setError(std::string("Failed to call method '")+name+"' with signature '"+signature+"'."); } } } /** * Calls a class method */ template<typename Return, typename... Args> Return staticCall(const std::string& name, const Return& defRet, Args&&... args){ std::string signature(createSignature(defRet, args...)); return staticCallSigned(name, signature, defRet, args...); } template<typename Return, typename... Args> Return staticCallSigned(const std::string& name, const std::string& signature, const Return& defRet, Args&&... args){ JNIEnv* env = getEnvironment(); if(!env){ return defRet; } jclass classId = getClass(); if(!classId){ return defRet; } jmethodID methodId = env->GetStaticMethodID(classId, name.c_str(), signature.c_str()); if (!methodId || env->ExceptionCheck()){ env->ExceptionClear(); setError(std::string("Failed to find static method '")+name+"'."); return defRet; }else{ jvalue* jargs = createArguments(args...); Return result = callStaticJavaMethod<Return>(env, classId, methodId, jargs); if (env->ExceptionCheck()){ env->ExceptionClear(); setError(std::string("Failed to call static method '")+name+"'."); return defRet; }else{ return result; } } } /** * Calls a class void method */ template<typename... Args> void staticCallVoid(const std::string& name, Args&&... args){ std::string signature(createVoidSignature(args...)); return staticCallSignedVoid(name, signature, args...); } template<typename... Args> void staticCallSignedVoid(const std::string& name, const std::string& signature, Args&&... args){ JNIEnv* env = getEnvironment(); if(!env){ return; } jclass classId = getClass(); if(!classId){ return; } jmethodID methodId = env->GetStaticMethodID(classId, name.c_str(), signature.c_str()); if (!methodId || env->ExceptionCheck()){ env->ExceptionClear(); setError(std::string("Failed to find static method '")+name+"'."); return; }else{ jvalue* jargs = createArguments(args...); callStaticJavaMethod<void>(env, classId, methodId, jargs); if (env->ExceptionCheck()){ env->ExceptionClear(); setError(std::string("Failed to call static method '")+name+"'."); } } } /** * Get a static class field * @param name the field name */ template<typename Return> Return staticField(const std::string& name, const Return& defRet){ std::string signature(getSignaturePart<Return>(defRet)); return staticFieldSigned(name, signature, defRet); } template<typename Return> Return staticFieldSigned(const std::string& name, const std::string& signature, const Return& defRet){ JNIEnv* env = getEnvironment(); if(!env){ return defRet; } jclass classId = getClass(); if(!classId){ return defRet; } jfieldID fieldId = env->GetStaticFieldID(classId, name.c_str(), signature.c_str()); if (!fieldId || env->ExceptionCheck()){ env->ExceptionClear(); setError(std::string("Failed to find static field '")+name+"' with signature '"+signature+"'."); return defRet; }else{ Return result = getJavaStaticField<Return>(env, classId, fieldId); if (env->ExceptionCheck()){ env->ExceptionClear(); setError(std::string("Failed to read static field '")+name+"' with signature '"+signature+"'."); return defRet; }else{ return result; } } } /** * Get a object field * @param name the field name */ template<typename Return> Return field(const std::string& name, const Return& defRet){ std::string signature(getSignaturePart<Return>(defRet)); return fieldSigned(name, signature, defRet); } template<typename Return> Return fieldSigned(const std::string& name, const std::string& signature, const Return& defRet){ JNIEnv* env = getEnvironment(); if(!env){ return defRet; } jclass classId = getClass(); if(!classId){ return defRet; } jfieldID fieldId = env->GetFieldID(classId, name.c_str(), signature.c_str()); if (!fieldId || env->ExceptionCheck()){ env->ExceptionClear(); setError(std::string("Failed to find field '")+name+"' with signature '"+signature+"'."); return defRet; }else{ Return result = getJavaField<Return>(env, classId, fieldId); if (env->ExceptionCheck()){ env->ExceptionClear(); setError(std::string("Failed to read field '")+name+"' with signature '"+signature+"'."); return defRet; }else{ return result; } } } /** * Return the signature for the object */ std::string getSignature() const; /** * Return the error */ const std::string& getError() const; /** * Return true of there is an error */ bool hasError() const; /** * create an java array of the given type */ template<typename Type> static jarray createJavaArray(JNIEnv* env, const Type& element, size_t size); /** * Convert a jobject array to a container */ template<typename Type> static bool convertFromJavaArray(JNIEnv* env, jarray arr, Type& container){ if(!arr){ return false; } jsize arraySize = env->GetArrayLength(arr); for(size_t i=0; i<arraySize; i++){ typename Type::value_type elm; convertFromJavaArrayElement(env, arr, i, elm); container.insert(container.end(), elm); } return true; } template<typename Type> static bool convertFromJavaArray(jarray arr, Type& container){ JNIEnv* env = getEnvironment(); assert(env); return convertFromJavaArray(env, arr, container); } /** * Get an element of a java array */ template<typename Type> static bool convertFromJavaArrayElement(JNIEnv* env, jarray arr, size_t position, Type& out); template<typename Type> static bool convertFromJavaArrayElement(JNIEnv* env, jarray arr, size_t position, std::vector<Type>& out){ jobject elm; if(!convertFromJavaArrayElement(env, arr, position, elm)){ return false; } return convertFromJavaArray(env, (jarray)elm, out); } template<typename Key, typename Value> static bool convertFromJavaArrayElement(JNIEnv* env, jarray arr, size_t position, std::map<Key, Value>& out){ jobject elm; if(!convertFromJavaArrayElement(env, arr, position, elm)){ return false; } return convertFromJavaMap(env, elm, out); } /** * Set an element of a java array */ template<typename Type> static void setJavaArrayElement(JNIEnv* env, jarray arr, size_t position, const Type& elm); template<typename Type> static bool convertFromJavaCollection(JNIEnv* env, jobject obj, Type& out){ if(!obj){ return false; } JniObject jcontainer(obj); if(!jcontainer.isInstanceOf("java.util.Collection")){ return false; } out = jcontainer.call<Type>("toArray", out, out); return true; } template<typename Key, typename Value> static bool convertFromJavaMap(JNIEnv* env, jobject obj, std::map<Key, Value>& out){ if(!obj){ return false; } JniObject jmap(obj); if(!jmap.isInstanceOf("java.util.Map")){ return false; } JniObject jkeys = jmap.call<JniObject>("keySet", JniObject("java.util.Set")); if(jkeys.hasError()){ return false; } std::vector<Key> keys = jkeys.callSigned<std::vector<Key>>("toArray", "()[Ljava/lang/Object;", std::vector<Key>()); for(typename std::vector<Key>::const_iterator itr = keys.begin(); itr != keys.end(); ++itr){ Value v = jmap.callSigned<Value>("get", "(Ljava/lang/Object;)Ljava/lang/Object;", Value(), *itr); out[*itr] = v; } return true; } template<typename Key, typename Value> static bool convertToMapFromJavaArray(JNIEnv* env, jarray arr, std::map<Key, Value>& out){ if(!arr){ return false; } jsize mapSize = env->GetArrayLength(arr) / 2; for(size_t i=0; i<mapSize; ++i){ Key k; if(convertFromJavaArrayElement(env, arr, i*2, k)){ Value v; if(convertFromJavaArrayElement(env, arr, i*2+1, v)){ out[k] = v; } } } return true; } /** * Convert a jobject to the c++ representation */ template<typename Type> static bool convertFromJavaObject(JNIEnv* env, jobject obj, Type& out); // template specialization for containers template<typename Type> static bool convertFromJavaObject(JNIEnv* env, jobject obj, std::vector<Type>& out){ if(convertFromJavaCollection(env, obj, out)){ return true; } if(convertFromJavaArray(env, (jarray)obj, out)){ return true; } return false; } template<typename Type> static bool convertFromJavaObject(JNIEnv* env, jobject obj, std::set<Type>& out){ if(convertFromJavaCollection(env, obj, out)){ return true; } if(convertFromJavaArray(env, (jarray)obj, out)){ return true; } return false; } template<typename Type, int Size> static bool convertFromJavaObject(JNIEnv* env, jobject obj, std::array<Type, Size>& out){ if(convertFromJavaCollection(env, obj, out)){ return true; } if(convertFromJavaArray(env, (jarray)obj, out)){ return true; } return false; } template<typename Type> static bool convertFromJavaObject(JNIEnv* env, jobject obj, std::list<Type>& out){ if(convertFromJavaCollection(env, obj, out)){ return true; } if(convertFromJavaArray(env, (jarray)obj, out)){ return true; } return false; } template<typename Key, typename Type> static bool convertFromJavaObject(JNIEnv* env, jobject obj, std::map<Key, Type>& out){ if(convertFromJavaMap(env, obj, out)){ return true; } if(convertToMapFromJavaArray(env, (jarray)obj, out)){ return true; } return false; } // utility methods that return the object template<typename Type> static Type convertFromJavaObject(JNIEnv* env, jobject obj){ Type out; bool result = convertFromJavaObject(env, obj, out); assert(result); return out; } template<typename Type> static Type convertFromJavaObject(jobject obj){ JNIEnv* env = getEnvironment(); assert(env); return convertFromJavaObject<Type>(env, obj); } template<typename Type> static bool convertFromJavaObject(jobject obj, Type& out){ JNIEnv* env = getEnvironment(); assert(env); return convertFromJavaObject(env, obj, out); } /** * Convert a c++ list container to a jarray */ template<typename Type> static jarray createJavaArray(const Type& obj){ JNIEnv* env = getEnvironment(); if (!env){ return nullptr; } jarray arr = nullptr; if(obj.empty()){ arr = createJavaArray(env, typename Type::value_type(), 0); }else{ arr = createJavaArray(env, *obj.begin(), obj.size()); } size_t i = 0; for(typename Type::const_iterator itr = obj.begin(); itr != obj.end(); ++itr){ setJavaArrayElement(env, arr, i, *itr); i++; } return arr; } template<typename Key, typename Value> static JniObject createJavaMap(const std::map<Key, Value>& obj, const std::string& classPath="java/util/HashMap"){ JniObject jmap(JniObject::createNew(classPath)); for(typename std::map<Key, Value>::const_iterator itr = obj.begin(); itr != obj.end(); ++itr){ Value v = jmap.callSigned("put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", Value(), itr->first, itr->second); } return jmap; } template<typename Type> static JniObject createJavaList(const Type& obj, const std::string& classPath="java/util/ArrayList"){ JniObject jlist(JniObject::createNew(classPath)); for(typename Type::const_iterator itr = obj.begin(); itr != obj.end(); ++itr){ jlist.callSignedVoid("add", "(Ljava/lang/Object;)Z", *itr); } return jlist; } template<typename Type> static JniObject createJavaSet(const Type& obj, const std::string& classPath="java/util/HashSet"){ return createJavaList(obj, classPath); } /** * Convert a c++ type to the jvalue representation * This is called on all jni arguments */ template<typename Type> static jvalue convertToJavaValue(const Type& obj); // template specialization for pointers template<typename Type> static jvalue convertToJavaValue(Type* obj){ return convertToJavaValue((jlong)obj); } // template specialization for containers template<typename Type> static jvalue convertToJavaValue(const std::vector<Type>& obj){ return convertToJavaValue(createJavaArray(obj)); } template<typename Type> static jvalue convertToJavaValue(const std::set<Type>& obj){ return convertToJavaValue(createJavaArray(obj)); } template<typename Type, int Size> static jvalue convertToJavaValue(const std::array<Type, Size>& obj){ return convertToJavaValue(createJavaArray(obj)); } template<typename Type> static jvalue convertToJavaValue(const std::list<Type>& obj){ return convertToJavaValue(createJavaArray(obj)); } template<typename Key, typename Value> static jvalue convertToJavaValue(const std::map<Key, Value>& obj){ return convertToJavaValue(createJavaMap(obj).getNewLocalInstance()); } /** * Returns the class reference. This is a global ref that will be removed * when the JniObject is destroyed */ jclass getClass() const; /** * Returns the class path. If it is not there it tries to call * `getClass().getName()` on the object to get the class */ const std::string& getClassPath() const; /** * Returns the jobject reference. This is a global ref that will be removed * when the JniObject is destroyed */ jobject getInstance() const; /** * Returns the jobject reference. This is a new local ref */ jobject getNewLocalInstance() const; /** * Return true if class path and class ref match */ bool isInstanceOf(const std::string& classPath) const; /** * Returns the environment pointer */ static JNIEnv* getEnvironment(); /** * Returns true if there is an object instance */ operator bool() const; /** * Copy a jni object */ JniObject& operator=(const JniObject& other); /** * Compare two jni objects */ bool operator==(const JniObject& other) const; }; #endif // JNIOBJECT_H |
jniobject.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 |
#include "jniobject.h" #include <algorithm> Jni::Jni():_java(nullptr), _env(nullptr){ } Jni::Jni(const Jni& other){ assert(false); } Jni::~Jni(){ if(!_classes.empty()){ JNIEnv* env = getEnvironment(); if(env){ for(ClassMap::const_iterator itr = _classes.begin(); itr != _classes.end(); ++itr){ env->DeleteGlobalRef(itr->second); } } } } Jni& Jni::get(){ static Jni jni; return jni; } JavaVM* Jni::getJava(){ return _java; } void Jni::setJava(JavaVM* java){ _java = java; } JNIEnv* Jni::getEnvironment(){ if(!_env){ assert(_java); int r = _java->GetEnv((void**)&_env, JNI_VERSION_1_6); assert(r == JNI_OK); (void)r; } int r = _java->AttachCurrentThread(&_env, nullptr); assert(r == 0); (void)r; return _env; } jclass Jni::getClass(const std::string& classPath, bool cache){ ClassMap::const_iterator itr = _classes.find(classPath); if(itr != _classes.end()){ return itr->second; } JNIEnv* env = getEnvironment(); if(env){ jclass cls = (jclass)env->FindClass(classPath.c_str()); if (cls){ if(cache){ cls = (jclass)env->NewGlobalRef(cls); _classes[classPath] = cls; return cls; }else{ return cls; } }else{ env->ExceptionClear(); } } return nullptr; } #pragma mark - JniObject JniObject::JniObject(const std::string& classPath, jobject objId, jclass classId) : _instance(nullptr), _class(nullptr){ init(objId, classId, classPath); } JniObject::JniObject(jclass classId, jobject objId) : _instance(nullptr), _class(nullptr){ init(objId, classId); } JniObject::JniObject(jobject objId) : _instance(nullptr), _class(nullptr){ init(objId); } JniObject::JniObject(const JniObject& other) : _instance(nullptr), _class(nullptr){ init(other._instance, other._class, other._classPath); } void JniObject::init(jobject objId, jclass classId, const std::string& classPath){ JNIEnv* env = getEnvironment(); _classPath = classPath; std::replace(_classPath.begin(), _classPath.end(), '.', '/'); if(env){ if(!classId){ if(objId){ classId = env->GetObjectClass(objId); }else if(!classPath.empty()){ classId = Jni::get().getClass(_classPath); } } if(classId){ _class = (jclass)env->NewGlobalRef(classId); }else{ _classPath = ""; } if(objId){ _instance = env->NewGlobalRef(objId); } } if(_classPath.empty() && _instance && _class){ _classPath = JniObject("java/lang/Class", _class).call("getName", std::string()); } if(!_class){ std::string err("Could not find class"); if(_classPath.empty()){ err += "."; }else{ err += " '"+_classPath+"'."; } setError(err); } } JniObject::~JniObject(){ clear(); } void JniObject::clear(){ JNIEnv* env = getEnvironment(); if(!env){ return; } if(_class){ env->DeleteGlobalRef(_class); _class = nullptr; } if(_instance){ env->DeleteGlobalRef(_instance); _instance = nullptr; } } std::string JniObject::getSignature() const{ return std::string("L")+getClassPath()+";"; } const std::string& JniObject::getError() const{ return _error; } bool JniObject::hasError() const{ return !_error.empty(); } void JniObject::setError(const std::string& msg){ _error = msg; } const std::string& JniObject::getClassPath() const{ return _classPath; } JNIEnv* JniObject::getEnvironment(){ return Jni::get().getEnvironment(); } jclass JniObject::getClass() const{ return _class; } jobject JniObject::getInstance() const{ return _instance; } jobject JniObject::getNewLocalInstance() const{ JNIEnv* env = getEnvironment(); if(!env){ return 0; } return env->NewLocalRef(getInstance()); } bool JniObject::isInstanceOf(const std::string& classPath) const{ std::string fclassPath(classPath); std::replace(fclassPath.begin(), fclassPath.end(), '.', '/'); JNIEnv* env = getEnvironment(); if(!env){ return false; } jclass cls = env->FindClass(fclassPath.c_str()); return env->IsInstanceOf(getInstance(), cls); } JniObject JniObject::findSingleton(const std::string& classPath){ JniObject cls(classPath); JniObject obj = cls.staticField("instance", cls); if(!obj){ obj = cls.staticCall("getInstance", cls); } if(!obj){ obj.setError("Could not find singleton instance."); } return obj; } JniObject::operator bool() const{ return getInstance() != nullptr; } JniObject& JniObject::operator=(const JniObject& other){ clear(); _classPath = other._classPath; init(other._instance, other._class); } bool JniObject::operator==(const JniObject& other) const{ JNIEnv* env = getEnvironment(); if(!env){ return false; } jobject a = getInstance(); jobject b = other.getInstance(); if(a && b){ return env->IsSameObject(a, b); } a = getClass(); b = other.getClass(); return env->IsSameObject(a, b); } #pragma mark - JniObject::getSignaturePart template<> std::string JniObject::getSignaturePart<std::string>(const std::string& val){ return "Ljava/lang/String;"; } template<> std::string JniObject::getSignaturePart(const JniObject& val){ return val.getSignature(); } template<> std::string JniObject::getSignaturePart(const bool& val){ return "Z"; } template<> std::string JniObject::getSignaturePart(const jboolean& val){ return "Z"; } template<> std::string JniObject::getSignaturePart(const jbyte& val){ return "B"; } template<> std::string JniObject::getSignaturePart(const jchar& val){ return "C"; } template<> std::string JniObject::getSignaturePart(const jshort& val){ return "S"; } template<> std::string JniObject::getSignaturePart(const jlong& val){ return "J"; } template<> std::string JniObject::getSignaturePart(const long& val){ return "J"; } template<> std::string JniObject::getSignaturePart(const jint& val){ return "I"; } template<> std::string JniObject::getSignaturePart(const unsigned int& val){ return "I"; } template<> std::string JniObject::getSignaturePart(const jfloat& val){ return "F"; } template<> std::string JniObject::getSignaturePart(const jobject& val){ return getSignaturePart(JniObject(val)); } std::string JniObject::getSignaturePart(){ return "V"; } #pragma mark - JniObject::convertToJavaValue template<> jvalue JniObject::convertToJavaValue(const bool& obj){ jvalue val; val.z = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const jboolean& obj){ jvalue val; val.z = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const jbyte& obj){ jvalue val; val.b = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const jchar& obj){ jvalue val; val.c = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const jshort& obj){ jvalue val; val.s = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const jint& obj){ jvalue val; val.i = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const unsigned int& obj){ jvalue val; val.i = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const long& obj){ jvalue val; val.j = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const jlong& obj){ jvalue val; val.j = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const jfloat& obj){ jvalue val; val.f = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const jdouble& obj){ jvalue val; val.d = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const jobject& obj){ jvalue val; val.l = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const JniObject& obj){ return convertToJavaValue(obj.getInstance()); } template<> jvalue JniObject::convertToJavaValue(const jarray& obj){ jvalue val; val.l = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const jstring& obj){ jvalue val; val.l = obj; return val; } template<> jvalue JniObject::convertToJavaValue(const std::string& obj){ JNIEnv* env = getEnvironment(); if (!env){ return jvalue(); } return convertToJavaValue(env->NewStringUTF(obj.c_str())); } #pragma mark - JniObject::convertFromJavaObject template<> bool JniObject::convertFromJavaObject(JNIEnv* env, jobject obj, std::string& out){ if(!obj){ out = ""; return true; } jstring jstr = (jstring)obj; const char* chars = env->GetStringUTFChars(jstr, NULL); if(!chars){ return false; } out = chars; env->ReleaseStringUTFChars(jstr, chars); return true; } template<> bool JniObject::convertFromJavaObject(JNIEnv* env, jobject obj, JniObject& out){ out = obj; env->DeleteLocalRef(obj); return true; } #pragma mark - JniObject call jni template<> void JniObject::callStaticJavaMethod(JNIEnv* env, jclass classId, jmethodID methodId, jvalue* args){ return env->CallStaticVoidMethodA(classId, methodId, args); } template<> jobject JniObject::callStaticJavaMethod(JNIEnv* env, jclass classId, jmethodID methodId, jvalue* args){ return env->CallStaticObjectMethodA(classId, methodId, args); } template<> double JniObject::callStaticJavaMethod(JNIEnv* env, jclass classId, jmethodID methodId, jvalue* args){ return env->CallStaticDoubleMethodA(classId, methodId, args); } template<> long JniObject::callStaticJavaMethod(JNIEnv* env, jclass classId, jmethodID methodId, jvalue* args){ return env->CallStaticLongMethodA(classId, methodId, args); } template<> jlong JniObject::callStaticJavaMethod(JNIEnv* env, jclass classId, jmethodID methodId, jvalue* args){ return env->CallStaticLongMethodA(classId, methodId, args); } template<> float JniObject::callStaticJavaMethod(JNIEnv* env, jclass classId, jmethodID methodId, jvalue* args){ return env->CallStaticFloatMethodA(classId, methodId, args); } template<> int JniObject::callStaticJavaMethod(JNIEnv* env, jclass classId, jmethodID methodId, jvalue* args){ return env->CallStaticIntMethodA(classId, methodId, args); } template<> std::string JniObject::callStaticJavaMethod(JNIEnv* env, jclass classId, jmethodID methodId, jvalue* args){ return convertFromJavaObject<std::string>(env, callStaticJavaMethod<jobject>(env, classId, methodId, args)); } template<> JniObject JniObject::callStaticJavaMethod(JNIEnv* env, jclass classId, jmethodID methodId, jvalue* args){ return convertFromJavaObject<JniObject>(env, callStaticJavaMethod<jobject>(env, classId, methodId, args)); } void JniObject::callJavaVoidMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args){ env->CallVoidMethodA(objId, methodId, args); } template<> void JniObject::callJavaMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args, jboolean& out){ out = env->CallBooleanMethodA(objId, methodId, args); } template<> void JniObject::callJavaMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args, jobject& out){ out = env->CallObjectMethodA(objId, methodId, args); } template<> void JniObject::callJavaMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args, double& out){ out = env->CallDoubleMethodA(objId, methodId, args); } template<> void JniObject::callJavaMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args, long& out){ out = env->CallLongMethodA(objId, methodId, args); } template<> void JniObject::callJavaMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args, jlong& out){ out = env->CallLongMethodA(objId, methodId, args); } template<> void JniObject::callJavaMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args, float& out){ out = env->CallFloatMethodA(objId, methodId, args); } template<> void JniObject::callJavaMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args, int& out){ out = env->CallIntMethodA(objId, methodId, args); } template<> void JniObject::callJavaMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args, std::string& out){ callJavaObjectMethod(env, objId, methodId, args, out); } template<> void JniObject::callJavaMethod(JNIEnv* env, jobject objId, jmethodID methodId, jvalue* args, JniObject& out){ callJavaObjectMethod(env, objId, methodId, args, out); } template<> jobject JniObject::getJavaStaticField(JNIEnv* env, jclass classId, jfieldID fieldId){ return env->GetStaticObjectField(classId, fieldId); } template<> double JniObject::getJavaStaticField(JNIEnv* env, jclass classId, jfieldID fieldId){ return env->GetStaticDoubleField(classId, fieldId); } template<> long JniObject::getJavaStaticField(JNIEnv* env, jclass classId, jfieldID fieldId){ return env->GetStaticLongField(classId, fieldId); } template<> jlong JniObject::getJavaStaticField(JNIEnv* env, jclass classId, jfieldID fieldId){ return env->GetStaticLongField(classId, fieldId); } template<> float JniObject::getJavaStaticField(JNIEnv* env, jclass classId, jfieldID fieldId){ return env->GetStaticFloatField(classId, fieldId); } template<> int JniObject::getJavaStaticField(JNIEnv* env, jclass classId, jfieldID fieldId){ return env->GetStaticIntField(classId, fieldId); } template<> std::string JniObject::getJavaStaticField(JNIEnv* env, jclass classId, jfieldID fieldId){ return convertFromJavaObject<std::string>(getJavaStaticField<jobject>(env, classId, fieldId)); } template<> JniObject JniObject::getJavaStaticField(JNIEnv* env, jclass classId, jfieldID fieldId){ return convertFromJavaObject<JniObject>(getJavaStaticField<jobject>(env, classId, fieldId)); } template<> jobject JniObject::getJavaField(JNIEnv* env, jobject objId, jfieldID fieldId){ return env->GetObjectField(objId, fieldId); } template<> double JniObject::getJavaField(JNIEnv* env, jobject objId, jfieldID fieldId){ return env->GetDoubleField(objId, fieldId); } template<> long JniObject::getJavaField(JNIEnv* env, jobject objId, jfieldID fieldId){ return env->GetLongField(objId, fieldId); } template<> float JniObject::getJavaField(JNIEnv* env, jobject objId, jfieldID fieldId){ return env->GetFloatField(objId, fieldId); } template<> int JniObject::getJavaField(JNIEnv* env, jobject objId, jfieldID fieldId){ return env->GetIntField(objId, fieldId); } template<> std::string JniObject::getJavaField(JNIEnv* env, jobject objId, jfieldID fieldId){ return convertFromJavaObject<std::string>(getJavaField<jobject>(env, objId, fieldId)); } template<> JniObject JniObject::getJavaField(JNIEnv* env, jobject objId, jfieldID fieldId){ return convertFromJavaObject<JniObject>(getJavaField<jobject>(env, objId, fieldId)); } template<> jarray JniObject::createJavaArray(JNIEnv* env, const jobject& element, size_t size){ jclass elmClass = env->GetObjectClass(element); return env->NewObjectArray(size, elmClass, 0); } template<> jarray JniObject::createJavaArray(JNIEnv* env, const double& element, size_t size){ return env->NewDoubleArray(size); } template<> jarray JniObject::createJavaArray(JNIEnv* env, const long& element, size_t size){ return env->NewLongArray(size); } template<> jarray JniObject::createJavaArray(JNIEnv* env, const jlong& element, size_t size){ return env->NewLongArray(size); } template<> jarray JniObject::createJavaArray(JNIEnv* env, const float& element, size_t size){ return env->NewFloatArray(size); } template<> jarray JniObject::createJavaArray(JNIEnv* env, const int& element, size_t size){ return env->NewLongArray(size); } template<> jarray JniObject::createJavaArray(JNIEnv* env, const std::string& element, size_t size){ jclass elmClass = env->FindClass("java/lang/String"); return env->NewObjectArray(size, elmClass, 0); } template<> jarray JniObject::createJavaArray(JNIEnv* env, const JniObject& element, size_t size){ jclass elmClass = element.getClass(); return env->NewObjectArray(size, elmClass, 0); } template<> bool JniObject::convertFromJavaArrayElement(JNIEnv* env, jarray arr, size_t position, jobject& out){ out = env->GetObjectArrayElement((jobjectArray)arr, position); return true; } template<> bool JniObject::convertFromJavaArrayElement(JNIEnv* env, jarray arr, size_t position, double& out){ env->GetDoubleArrayRegion((jdoubleArray)arr, position, 1, &out); return true; } template<> bool JniObject::convertFromJavaArrayElement(JNIEnv* env, jarray arr, size_t position, long& out){ jlong jout = 0; env->GetLongArrayRegion((jlongArray)arr, position, 1, &jout); out = jout; return true; } template<> bool JniObject::convertFromJavaArrayElement(JNIEnv* env, jarray arr, size_t position, jlong& out){ env->GetLongArrayRegion((jlongArray)arr, position, 1, &out); return true; } template<> bool JniObject::convertFromJavaArrayElement(JNIEnv* env, jarray arr, size_t position, float& out){ env->GetFloatArrayRegion((jfloatArray)arr, position, 1, &out); return true; } template<> bool JniObject::convertFromJavaArrayElement(JNIEnv* env, jarray arr, size_t position, int& out){ env->GetIntArrayRegion((jintArray)arr, position, 1, &out); return true; } template<> bool JniObject::convertFromJavaArrayElement(JNIEnv* env, jarray arr, size_t position, std::string& out){ jobject obj; if(!convertFromJavaArrayElement(env, arr, position, obj)){ return false; } convertFromJavaObject(env, obj, out); return true; } template<> bool JniObject::convertFromJavaArrayElement(JNIEnv* env, jarray arr, size_t position, JniObject& out){ jobject obj; if(!convertFromJavaArrayElement(env, arr, position, obj)){ return false; } convertFromJavaObject(env, obj, out); return true; } template<> void JniObject::setJavaArrayElement(JNIEnv* env, jarray arr, size_t position, const jobject& elm){ env->SetObjectArrayElement((jobjectArray)arr, position, elm); } template<> void JniObject::setJavaArrayElement(JNIEnv* env, jarray arr, size_t position, const double& elm){ env->SetDoubleArrayRegion((jdoubleArray)arr, position, 1, &elm); } template<> void JniObject::setJavaArrayElement(JNIEnv* env, jarray arr, size_t position, const long& elm){ jlong jelm = elm; env->SetLongArrayRegion((jlongArray)arr, position, 1, &jelm); } template<> void JniObject::setJavaArrayElement(JNIEnv* env, jarray arr, size_t position, const jlong& elm){ jlong jelm = elm; env->SetLongArrayRegion((jlongArray)arr, position, 1, &jelm); } template<> void JniObject::setJavaArrayElement(JNIEnv* env, jarray arr, size_t position, const float& elm){ env->SetFloatArrayRegion((jfloatArray)arr, position, 1, &elm); } template<> void JniObject::setJavaArrayElement(JNIEnv* env, jarray arr, size_t position, const int& elm){ env->SetIntArrayRegion((jintArray)arr, position, 1, &elm); } template<> void JniObject::setJavaArrayElement(JNIEnv* env, jarray arr, size_t position, const std::string& elm){ jobject obj = env->NewStringUTF(elm.c_str()); setJavaArrayElement(env, arr, position, obj); } template<> void JniObject::setJavaArrayElement(JNIEnv* env, jarray arr, size_t position, const JniObject& elm){ setJavaArrayElement(env, arr, position, elm.getInstance()); } |
JavaNatives.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
package com.damrakoc.blog.JavaNatives; import android.app.Activity; import android.content.Context; import android.util.Log; import me.leolin.shortcutbadger.ShortcutBadger; /** * Created by damra on 18.02.2017. */ public class JavaNatives { static String TAG = "JavaNatives"; public static JavaNatives instance; private JavaNatives (){ } public static JavaNatives getInstance() { if (instance == null) { synchronized (getInstance()) { if (instance == null) { instance = new JavaNatives(); } } } return instance; } static { Log.d(TAG, "Static initializer"); } String doSomething() { return "OK"; } // declare the native functions // these functions will be called by the BroadcastReceiver object // when it receives a new notification private static native synchronized void setNotificationBadge(int badgeCount); // This static method is called by C/C++ to register the BroadcastReceiver public static void SetBadge(final Activity activity, final int badgeCount){ Log.d(TAG, "SetBadge: "+badgeCount); Context context = activity.getApplication().getApplicationContext(); ShortcutBadger.applyCount(context, badgeCount); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
#ifndef ANDROIDUTIL_H #define ANDROIDUTIL_H #include <QApplication> #include "jniobject.h" #if defined(Q_OS_ANDROID) #include <QAndroidJniObject> #include <QAndroidJniEnvironment> #include <QtAndroid> #include <qpa/qplatformnativeinterface.h> QAndroidJniObject getMainActivity(); QAndroidJniObject getMainActivity(){ QPlatformNativeInterface * interface = QApplication::platformNativeInterface(); QAndroidJniObject activity = (jobject)interface->nativeResourceForIntegration("QtActivity"); if(!activity.isValid()) qDebug()<<"CLASS IS INVALID!"; else qDebug()<<"CLASS IS VALID!"; return activity; } #endif #ifdef __cplusplus extern "C" { #endif class Notification { private: long mCount; public: Notification(long count){ qDebug() <<"Constructor called"; mCount = count; } ~ Notification() { qDebug() << "Destructor called"; } }; static void setNotificationBadge (jstring jresult, jlong jptr){ Notification* data = (Notification*)jptr; if(!data) { return; } std::string result; JniObject::convertFromJavaObject(jresult, result); // do C++ something delete data; } // Get the JNI environment. JNIEnv* GetJniEnv() { Jni::get().getEnvironment(); } // Get the activity. jobject GetActivity() { return QtAndroid::androidActivity().object<jobject>(); } // Get the window context. For Android, it's a jobject pointing to the Activity. jobject GetWindowContext() { return QtAndroid::androidActivity().object<jobject>(); } // http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html // CPP Wrapper Interface for Java static JNINativeMethod methods[] = { { "setNotificationBadge","(Ljava.lang.String;I)V",(void*)setNotificationBadge}, }; JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*){ qDebug() << ("JNI_OnLoad"); Jni::get().setJava(vm); JniObject native = JniObject("JavaNatives").getInstance(); std::string result = native.call("doSomething", std::string()); qDebug() << QString::fromUtf8(result.c_str()); return JNI_VERSION_1_6; } #ifdef __cplusplus } #endif #endif // ANDROIDUTIL_H |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// main.cpp #include <QGuiApplication> #include <QDebug> #include "android-util.h" int main(int argc, char *argv[]){ QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); #if defined(__ANDROID__) QtAndroid::hideSplashScreen(); #endif // defined(__ANDROID__) return app.exec(); } |