当前位置:网站首页>[mixed programming JNI] Part 6: operation of strings and arrays in native
[mixed programming JNI] Part 6: operation of strings and arrays in native
2022-06-26 22:07:00 【Hua Weiyun】
continue JNI Knowledge points of , Today, let's look at some operations of strings and arrays
These two are special existence
String manipulation
Coding format
Java By default Unicode code ,C/C++ By default UTF code
When manipulating strings in local code ,JNI Support string in Unicode and UTF-8 Conversion between two codes .
GetStringUTFChars Be able to put a jstring The pointer ( Point to JVM Inside Unicode Character sequence ) Convert to a UTF-8 Format C character string .
Access string
Generally speaking , In from JVM After getting a string internally .
JVM A new piece of memory will be allocated internally , Copy the original string , So that local code can access and change .
That is, there is a memory allocation . It should be released after use .
ReleaseStringUTFChars() and GetStringUTFChars() They have to come in pairs , Used to free memory and references , Enables objects to be GC Recycling .
Create string
call NewStringUTF Function will build a new java.lang.String String object .
JVM Unable to allocate enough memory ,NewStringUTF Will throw out a OutOfMemoryError abnormal , And back to NULL
Here is a series of moves
jstring NewStringUTF(JNIEnv *env, const char *bytes); jsize GetStringUTFLength(JNIEnv *env, jstring string);void ReleaseStringUTFChars(JNIEnv *env, jstring string,const char *utf);Two sets of functions GetStringRegion and GetStringUTFRegion
void GetStringRegion(JNIEnv *env, jstring str, jsize start, jsize len, jchar *buf);void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize len, char *buf);The above two functions are to copy a paragraph buff Array , Avoid all copies .
Recommended GetStringUTFRegion
GetStringCritical and ReleaseStringCriticalconst jchar * GetStringCritical(JNIEnv *env, jstring string, jboolean *isCopy);void ReleaseStringCritical(JNIEnv *env, jstring string, const jchar *carray);GetStringCritical What you get is a point JVM A direct pointer to an internal string , Getting this direct pointer will cause a pause GC Threads The message here is jvm The internal pointer , Be careful , Use with caution
Array operation
The naming rules for array operations are operate + PrimitiveType + Array
Through the first GetXXXArrayElements Function to convert an array of simple types into an array of local types ,
And return a pointer to its array , This pointer is then used to process the copied array .
After processing the copy array , adopt ReleaseXXXArrayElements Function to reflect the modified copy array to java Array ,
Basic operation
// Get the array length jsize (GetArrayLength)(JNIEnv env, jarray array);// Create array jobjectArray NewObjectArray (JNIEnv *env, jsize length, jclass elementClass, jobject initialElement);// Get elements NativeType *Get<PrimitiveType>ArrayElements(JNIEnv *env,ArrayType array, jboolean *isCopy);// Set up the data void SetObjectArrayElement(JNIEnv *env, jobjectArray array,jsize index, jobject value)// Release the elements void Release<PrimitiveType>ArrayElements(JNIEnv *env,ArrayType array, NativeType *elems, jint mode);elems The parameter is a function of using the corresponding GetPrimitiveTypeArrayElements() The function is defined by array Exported pointer .
When necessary, , This function will put the pair elems The modification of is copied back to the array of basic types .mode Parameter will provide information about how to free the array buffer .
If elems No array A copy of an array element in ,mode Will be invalid .
otherwise ,mode It will have the functions described in the following table :

Local access
// Copy the contents of the array to C In the buffer void Get<PrimitiveType>ArrayRegion(JNIEnv *env, ArrayType array,jsize start, jsize len, NativeType *buf);// Copy the contents of the buffer to the array void Set<PrimitiveType>ArrayRegion(JNIEnv *env, ArrayType array,jsize start, jsize len, const NativeType *buf);A set of functions used to copy an area of an array of basic types into a buffer / A set of functions that copies a region of an array of basic types from the buffer
Direct access
void * GetPrimitiveArrayCritical(JNIEnv *env, jarray array, jboolean *isCopy);void ReleasePrimitiveArrayCritical(JNIEnv *env, jarray array, void *carray, jint mode);Returns a direct pointer to an array of specified underlying data types , No blocking operation can be done between these two operations
For example
Pass array to C++
// Java Pass on Array To C++ Perform array summation private native int intArraySum(int[] intArray, int size);C++ Side code
JNIEXPORT jint JNICALLJava_com_demo_intArraySum(JNIEnv *env, jobject instance, jintArray intArray_, jint num) { jint *intArray; int sum = 0; // Operation method 1 : // Like getUTFString equally , Will apply for native Memory intArray = env->GetIntArrayElements(intArray_, NULL); if (intArray == NULL) { return 0; } // Get the length of the array int length = env->GetArrayLength(intArray_); cout<<"array length is "<<length; for (int i = 0; i < length; ++i) { sum += intArray[i]; } cout<<"sum is " <<sum); // Operation method 2 : jint buf[num]; // adopt GetIntArrayRegion Method to get the contents of the array env->GetIntArrayRegion(intArray_, 0, num, buf); sum = 0; for (int i = 0; i < num; ++i) { sum += buf[i]; } cout<<"sum is "<<sum; // Don't forget to free the memory after using it env->ReleaseIntArrayElements(intArray_, intArray, 0); return sum;}C++ Return array to Java
// from C++ Returns an array of basic data types private native int[] returnIntArray(int num);/** * from Native return int Array , Main call set<Type>ArrayRegion To fill in the data , Other data types operate similarly */extern "C"JNIEXPORT jintArray JNICALLJava_demo_returnIntArray(JNIEnv *env, jobject instance, jint num) { jintArray intArray; intArray = env->NewIntArray(num); jint buf[num]; for (int i = 0; i < num; ++i) { buf[i] = i * 2; } // Use setIntArrayRegion To assign a value env->SetIntArrayRegion(intArray, 0, num, buf); return intArray;}summary
This article mainly writes the operation of string and array
Basically, all you have to remember is get ,set ,region as well as release A few key words
Application memory , Free memory , Get elements , Operational elements
边栏推荐
- 打新债注册开户有没有什么风险?安全吗?
- Introduction to dependency injection in SAP Spartacus
- Is this a bug? Whether the randomly filled letters can be closed
- Is there any risk in registering and opening an account for stock speculation? Is it safe?
- 【混合编程jni 】第十二篇 jnaerator
- 【混合编程jni 】第十一篇之JNA详情
- Web crawler 2: crawl the user ID and home page address of Netease cloud music reviews
- Implementation of collaborative filtering evolution version neuralcf and tensorflow2
- SAP Commerce Cloud 项目 Spartacus 入门
- Module 5 operation
猜你喜欢

leetcode:6103. 从树中删除边的最小分数【dfs + 联通分量 + 子图的值记录】
![[mathematical modeling] spanning tree based on Matlab GUI random nodes [including Matlab source code 1919]](/img/0c/17efaaa2488451b6dd15d9db33eba7.jpg)
[mathematical modeling] spanning tree based on Matlab GUI random nodes [including Matlab source code 1919]

WordPress collection plug-ins are recommended to be free collection plug-ins

Product design in the extreme Internet Era

Kdd2022 𞓜 unified session recommendation system based on knowledge enhancement prompt learning
![leetcode:141. Circular linked list [hash table + speed pointer]](/img/19/f918f2cff9f831d4bbc411fe1b9776.png)
leetcode:141. Circular linked list [hash table + speed pointer]

Web crawler 2: crawl the user ID and home page address of Netease cloud music reviews

VB. Net class library to obtain the color under the mouse in the screen (Advanced - 3)

CVPR 2022 | 美团技术团队精选论文解读

Yolov6: un cadre de détection de cibles rapide et précis est Open Source
随机推荐
协同过滤进化版本NeuralCF及tensorflow2实现
Centos7编译安装Redis
Configuring assimp Library in QT environment (MinGW compiler)
Vulnhub's dc9
Unity3D插件 AnyPortrait 2D骨骼动画制作
MacOS環境下使用HomeBrew安裝[email protected]
vulnhub之dc8
「连续学习Continual learning, CL」最新2022研究综述
Common configuration of jupyterlab
Briefly describe the model animation function of unity
Which securities company is the most convenient, safe and reliable for opening an account
Release of dolphin scheduler video tutorial in Shangsi Valley
关于appium踩坑 :Encountered internal error running command: Error: Cannot verify the signature of (已解决)
leetcode:6103. Delete the minimum score of the edge from the tree [DFS + connected component + value record of the subgraph]
How to enable Hana cloud service on SAP BTP platform
leetcode:152. 乘积最大子数组【考虑两个维度的dp】
Yolov6: un cadre de détection de cibles rapide et précis est Open Source
证券注册开户有没有什么风险?安全吗?
Some ways out for older programmers
VB. Net class library (Advanced - 2 overload)