JNI memory allocation

Boehm, Hans hans_boehm@hp.com
Mon Jun 16 22:28:00 GMT 2003


My reaction:
1) I'd be inclined to either write portable JNI code or stick to CNI.
2) Sticking pointers into jints is not recommended. On 64-bit machines they don't fit.
3) I'm not sure what the best way is to allocate collectable untraced memory from
CNI. You want something like _Jv_AllocBytes, which you presumably shouldn't use.
The collector call is GC_MALLOC_ATOMIC, which you probably shouldn't use directly
either. JvNewByteArray does a bunch of extra work. Tom?
4) The collector should handle the interior pointer into the array object correctly,
but only if the pointer is in an automatic (stack) variable. That makes this a bit
brittle for my taste. _Jv_AllocBytes wouldn't have this problem.
Hans
> -----Original Message-----
> From: Simon Gornall [mailto:gcj@gornall.net]
> Sent: Saturday, June 14, 2003 2:43 PM
> To: java@gcc.gnu.org
> Subject: JNI memory allocation
>>> Hi all,
>> I'm porting a java wrapper for the (http://www.libsdl.org) 
> SDL library 
> to JNI, and was hoping to use things like JvNewByteArray for 
> the memory 
> allocated within the native C++ calls. It struck me, though, that the 
> existing code passes handles (as jint's) back from the C++ 
> code to the 
> java world, and vice versa when calling native code. If this is the 
> case, won't the garbage collector consider the memory (which is only 
> referenced via the handle, which Java thinks is an int, not a 
> pointer) 
> fair game for collection at any time ?
>> As an example, there are constructs like:
>> jint sdl::event::EventDispatcher::SDLPollEvent(jint handle)
> {
> SDL_Event *event = NULL;
>> if (handle==0)
> {
> // old code commented out and replaced by JvNewByteArray
> // event = (SDL_Event *)malloc(sizeof(SDL_Event));
>> jbyteArray array = JvNewByteArray(sizeof(SDL_Event));
> event = (SDL_Event *) elements(array);
> }
> else
> event = (SDL_Event *)handle;
>> if (event != NULL)
> {
> event->type = SDL_NOEVENT;
> SDL_PollEvent(event);
> return (jint)event;
> }
>> return 0;
> }
>>> Once the handle is returned, it's used to refer to the event later on 
> for processing as different types etc.
>> So, is it safe to use JvNewByteArray in this sort of context, 
> or is it 
> dangerous ?
>> Thanks in advance for any help - much appreciated :-))
>> ATB,
> Simon
>>


More information about the Java mailing list

AltStyle によって変換されたページ (->オリジナル) /