kivy / pyobjus

Access Objective-C classes from Python
https://pyobjus.readthedocs.io
MIT License
178 stars 47 forks source link

Suggestion: add ability add user defined @protocols #78

Closed teticio closed 10 months ago

teticio commented 3 years ago

My understanding is that there are currently no plans to be able to handle custom blocks as a generally accepted work around seems to be to implement some bridging code in Objective C. While it would be great (and somehow satisfying) if it were possible to do everyhting from Python, I still find the need to callback my Python code. Please tell me if there is a better way of doing this without grunging around in the details of Objective C, but I am using the @protocol functionality. When an function from a Framework calls a delegate, for example, this works very well in pyobjus. Unfortunately, it doesn't seem possible to define your own delegates, so I am having to "hack" an existing one like so:

test.m:

#include <Foundation/Foundation.h>
#include <AVFoundation/AVFoundation.h>

@interface MyObjCClass : NSObject {}
+ (void) testWithDelegate: (id<AVAsynchronousKeyValueLoading>) delegate
@end

@implementation MyObjCClass
+ (void) testWithDelegate: (id<AVAsynchronousKeyValueLoading>) delegate
{
    [delegate statusOfValueForKey: @"This is a test" error: nil];
}
@end

test.py:

from pyobjus import autoclass, protocol

MyObjCClass = autoclass('MyObjCClass')

Class Test():
    def __init__(self):
        MyObjCClass.testWithDelegate_(self)

    # massive hack!
    @protocol('AVAsynchronousKeyValueLoading')
    def statusOfValueForKey_error_(self.message, error):
        Logger.info(f"{message.UTF8String()}")  # outputs "This is a test"

FWIW, I'd be happy to contribute to this project, if that is helpful. If you encourage this, are there any basic guidelines or tips I should follow?

Thanks!

Julian-O commented 10 months ago

There is a mailing list and a Discord channel to support Kivy users debugging their own systems, which should be able to help. They are linked in the ReadMe.