Re: [Pyobjc-dev] Is this real?
Brought to you by:
ronaldoussoren
From: b.bum <bb...@ma...> - 2004-05-23 16:03:14
|
Calling from ObjC -> Python works fine, it is the only way that we can build full featured Cocoa applications entirely in Python. Messaging new Python classes from ObjC is a slight challenge just because you don't have the class around when you compile the ObjC. This is analogous to writing code that messages a class that is in a Bundle -- there is a total chicken and egg problem (and a linker problem too, if you aren't careful). It isn't hard, just need to get it right. - use the embedded-interpreter-main in your app to embed and initialize the python interpreter and start up PyObjC - nothing else in your app has to be modified (or pythonified) - add the appropriate import statements to __main__.py to make sure your classes are defined - in __main__.py, instantiate your python stuff and pass the python classes into ObjC NSApp().delegate().setThePythonCalculator_(new MyPythonClass()) ... where your application's delegate implements -(void)setThePythonCalculator: (id)someObject and -retains someObject for as long as it needs (likely in an instance variable - message someObject as you would almost normally: - you can likely only pass objects into the Python side; NSString, NSNumber, arrays, etc... This is similar to KeyValueCoding's internal behavior. - you will likely need to declare the python side methods somewhere in a header to avoid compiler warnings. This isn't a big deal, just define a PythonClass like this: @interface PythonClass:NSObject ... methods from python go here @end @implementation ... stub implementations here; don't do anything @end Then, you can just cast someObject to an instance of PythonClass and your compiler warnings will go away. - the python API will need to be declared with '_'s for each argument -- i.e. the python API will need to translate to an ObjC API via the same '_' -> ':' -> '_" rules as the rest of PyObjC. There will be a couple of issues in going this route because pure python objects don't behave entirely like NSObject subclasses. This isn't a limit of the bridge, but fallout from having multiple root classes. The NSObject root classes offers a bunch of behavior that various parts of the AppKit and Foundation rely upon -- pure python objects don't offer that. Not a big deal, if you can just declare your python side classes as subclasses of NSObject: class Foo(NSObject): pass If you have a pure python class that you want to bridge, you may have some success doing this: >>> class Foo: ... def bar(self):print "baz" ... >>> class Bar(NSObject, Foo): ... pass ... >>> Bar <objective-c class Bar at 0x366170> >>> Foo <class __main__.Foo at 0x2132f00> >>> x = Bar.new() >>> x <Bar: 0x3dbd10> >>> x.bar() baz >>> x.description() u'<Bar: 0x3dbd10>' >>> |