rubicon-objc icon indicating copy to clipboard operation
rubicon-objc copied to clipboard

Needs documentation on how to pass an pointer-to-pointer “out parameter”

Open uranusjr opened this issue 9 years ago • 1 comments

It is common in Cocoa API for a method to have an “out parameter”, e.g. an NSError ** parameter that is used to return an error when a call fails.

Taking the deserialisation method in NSJSONSerialization for example, this method

+ (id)JSONObjectWithData:(NSData *)data
                 options:(NSJSONReadingOptions)opt
                   error:(NSError **)error

can be called like this in Objective-C:

NSError *err = nil;
id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];

And the equivalent with Rubicon-objc would be

from ctypes import byref, c_void_p

err = c_void_p(0)
obj = NSJSONSerialization.JSONObjectWithData_options_error_(
    data, 0, byref(err),
)

NB: err = None will not work since byref expects a ctypes instance, and does not automatically convert None to a NULL pointer.

uranusjr avatar May 07 '15 14:05 uranusjr

Agreed that this should be in the docs.

One additional detail - once you've got your err object, you can turn it into an actual ObjCInstance of whatever type you want by using:

error = NSError(err)

That is - if all you have is a pointer to an ObjC instance, you can create a wrapped object using the Python constructor for the relevant class. You can then invoke methods on the ObjC instance as you would one that you had instantiated using NSError.alloc().init() or NSError.new().

freakboy3742 avatar May 08 '15 00:05 freakboy3742