Storing C++ data in an instance field using CNI?

Bryce McKinlay mckinlay@redhat.com
Wed May 26 16:17:00 GMT 2004


Stanley Brown wrote:
>>> is it possible using CNI to store C++ data in the object as an
>>> instance field?
>> As earlier mentioned the best way to do this is to store the struct 
> address in a long java variable. Why long? Well, to be honest 64-bit 
> systems will eventually become the norm which means you will probably 
> have to convert your program later. Think ahead now and write it for 
> 64 bit systems in mind since that will still work with 32 bit systems 
> (just get alot of warnings during compilation about casting int to long).

If this is for CNI, the recommended type to use is RawData. This will be 
pointer-length no matter what system you compile it on.
> Also remember to override the finalize method of your Java object that 
> is storing the native struct to call a native method to free/delete 
> the native struct. Very important!! If you dont do this C/C++ will 
> not deallocate the memory reserved for your native struct when the 
> Java class is GCed.

I'm thinking of adding something like "RawDataMarked" which would be 
like RawData but would be checked by the GC. This way you could allocate 
a native struct using JvAllocBytes(), and it would be automatically 
freed when the Java object becomes unreachable. No need for a finalizer.
Thoughts? Anyone got an idea for a better name for it?
Regards
Bryce


More information about the Java mailing list

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