开发者

What is the object lifetime of a jstring in JNI?

I don't have much knowledge about JNI and how things are handled inside JNI environment. I have a simple questio开发者_运维技巧n.

I have a method in in Java which calls a JNI method and passes a String in parameter . JNI method accepts that string in a jstring object and stores it in a static vector<jstring>.

My question: Is this safe to use this vector throughout the life cycle of java application? Do I need to consider the fact the GC may move String in Java environment? Will that cause any problem in this situation? if yes, what should be the right way?


It may or may not be ok, basically the VM gives you very little promises on what happens to the memory used by jstrings after the JNI call

Pretty much straight from the source: http://java.sun.com/docs/books/jni/html/objtypes.html

The JNI passes objects to native methods as opaque references. Opaque references are C pointer types that refer to internal data structures in the Java virtual machine. The exact layout of the internal data structures, however, is hidden from the programmer. The native code must manipulate the underlying objects via the appropriate JNI functions, which are available through the JNIEnv interface pointer. For example, the corresponding JNI type for java.lang.String is jstring. The exact value of a jstring reference is irrelevant to the native code. The native code calls JNI functions such as GetStringUTFChars (§3.2.1) to access the contents of a string.

So long story short, you shouldnt be accessing the value of the jstring directly anyhow, so there is no reason to store the jstrings, use the appropriate methods to convert them to native strings and store them that way.


Is this safe to use this vector throughout the life cycle of java application?

No. See the JNI specification Ch. 2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜