Re: Newbie question: getting an object back from just a pointer
Re: Newbie question: getting an object back from just a pointer
- Subject: Re: Newbie question: getting an object back from just a pointer
- From: Steve Christensen <email@hidden>
- Date: Sat, 24 Feb 2007 08:05:33 -0800
On Feb 24, 2007, at 4:35 AM, Chris Adamson wrote:
I'm writing a Java-to-native library to wrap QTKit. At ADC's
suggestion, my plan for mapping Java objects to Obj-C objects is to
hold onto the pointer to an Obj-C object in the form of a long on
the Java side. That way, when I make a call to QTKit, I'll need to
pass in the longs of all the relevant QTKit objects.
My problem is recreating Cocoa objects from their pointers.
The following code creates a QTMovie object (the NSURL and NSError
are originally packed into an array because I had to use
performSelectorOnMainThread:, and thus had to pack my arguments
into an array to get them to that selector):
NSURL* url = (NSURL*) [args objectAtIndex:0];
NSError* initError = (NSError*) [args objectAtIndex:1];
QTMovie* movie = [QTMovie movieWithURL:url error:&initError];
My problem -- and I'm sure this is just me being stupid with
pointers, sorry -- is casting that pointer to a QTMovie object,
which I'll need to do when I come back from a Java call. I've
tried to do so right here as a sort of test:
// let's just test that, shall we?
NSLog (@"SelectorHelper re-casting movie...");
QTMovie* movieTest = (QTMovie*) &movie;
NSLog (@"Re-cast movie is %@", movieTest);
Unfortunately, this is a crasher, and I never see the second NSLog.
I think I'm either mangling the pointer, or profoundly
misunderstanding how to get back to an object, given just its
address (i.e., &movie). Unless it's something stupider, like I'm
not retaining the movie and it's already gone five lines later?
I believe all you need to do is:
QTMovie* movie = [[QTMovie movieWithURL:url error:&initError]
retain];
Otherwise the movie object is marked autorelease and has disappeared
on you before you get a chance to use it again.
Of course, you also need to make sure that when you convert it to a
Java number, that the number type is at least the same size as the
original pointer (i.e., 32 bits on a 32-bit architecture, 64 bits on
a 64-bit architecture, etc.).
steve
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden