I want to call a C function from my ObjC. I am passing a C function reference (defined in ObjC) in a C struct so that C can call that function. I also want to pass the reference to a completion-block to C, so that when I get a callback, I can call that completion-block. But I do not know how to implement that. I get different errors based on the different typecasting I tried.
//Abc.m
void myCallback(MyData *data)
{
//I get the control here!
//((__bridge void *)(data->completionBlock))([NSString stringWithCString:data->json]); //how to call the completion block?
}
- (void)myMethod:(NSString)input
completion:(void (^)(NSString * _Nullable response))completionBlock
{
MyData *data = malloc(sizeof(MyData));
data->myCallback = myCallback;
data->completionBlock = (__bridge void *)(completionBlock);//is this correct?
cFunction(data);
}
//Xyz.c
typedef struct
{
char *json;
void (*myCallback)(void *response);
void *completionBlock;
} MyData;
void cFunction(MyData *data)
{
data->json = "some response";
(data->myCallback)(data);
}
There are two issues to consider:
Casting: You need to cast to appropriate types, e.g. your commented out (__bridge void *)(data->completionBlock) doesn't give you back a block type so the compiler will reject the call.
Ownership: Blocks are just objects in Objective-C and are managed by ARC for you. In C blocks are manually managed. You must ensure that the block you pass into your C structure will not be released by ARC, and having used it you must ensure that it is freed.
Following your code design let's first define a type to make things easier:
typedef void (^CompletionBlock)(NSString * _Nullable response);
With that your myMethod function starts as before:
- (void)myMethod:(NSString*)input
completion:(CompletionBlock)completionBlock
{
MyData *data = malloc(sizeof(MyData));
data->myCallback = myCallback;
Now you must store your block into your struct while making sure ARC does not release it on the Objective-C side. To do that you use __bridge_retain which returns a retained reference to the block, your code will be responsible for balancing that retain. That can either be done in your C code or you can transfer the ownership back to ARC and let it take care of it. So the remainder of myMethod is:
data->completionBlock = (__bridge_retained void *)(completionBlock);
cFunction(data);
}
Now your cFunction just calls your myCallBack function so in this case there is no need to change anything there.
Now to your myCallBack, first we fix the type mismatch and define it to take a void * and then recover the MyData *:
void myCallback(void *response)
{
MyData *data = response;
Now we need to recover the block. We could just cast it to the block type, but that would leave us with the job of freeing it (using Block_release()) after we've used it; however we can use __bridge_transfer to hand back ownership to ARC so it will manage it:
CompletionBlock completionBlock = (__bridge_transfer CompletionBlock)data->completionBlock;
Now we get the string out and convert it to an NSString:
NSString *result = [NSString stringWithCString:data->json encoding:NSUTF8StringEncoding];
And then free the malloc'ed wrapper:
free(data);
Finally we call the block:
completionBlock(result);
}
The above followed your design, but there is no need to have your C function call another C function in your Objective-C file to call the block - blocks are a C language feature and supported in .c files by Clang. You can just cast data->completionBlock to the block type, invoke it, and then use Block_release() to free the block.
Further as blocks are C types you can type the struct field completionBlock with a block type and remove a lot of casts (but those cases cost nothing at runtime).
HTH
__bridge means to use c style pointer, its behaviour like assign or __unsafe_unretained.
You use it mean data->completionBlock just point to completionBlock without retain, so you may crash when completionBlock has been released.
If you wanna access block or objective-c object in struct with ARC, you have to declare these with __unsafe_unretained and manager their life by yourself.
typedef struct {
char *json;
__unsafe_unretained NSString *name;
__unsafe_unretained CompletionBlock block;
} SampleStruct;
Related
Upon receiving an NSString, I would like to call a specific code block. I figured an NSDictionary would be best for associating these. Simplified, I'm using something like:
MyProtocol.h:
#protocol MyProtocol <NSObject>
typedef void (^Handler)(id<MyProtocol> obj, id data);
#end
MyClass.h:
#interface MyClass : NSObject <MyProtocol>
- (void)aMethodWithString:(NSString *)string andData:(id)data;
#end
MyClass.m:
#interface MyClass ()
void myCommandHandler(id<MyProtocol> obj, id data); // matches signature defined in protocol
#end
#implementation MyClass
void myCommandHandler(id<MyProtocol> obj, id data)
{
// ...
}
- (void)aMethodWithString:(NSString *)string andData:(id)data
{
static NSDictionary<NSString *, Handler> *handler;
static dispatch_once_t onceToken;
// don't allocate this dictionary every time the function is called
dispatch_once(&onceToken,
^{
handler =
#{
#"MyCommand":myCommandHandler,
};
});
// ... error checking, blah blah ...
Handler block;
if ((block = handler[string]))
{ block(self, data); }
}
#end
Using this, I get an error in the dictionary literal construction:
Collection element of type 'void (__strong id<MyProtocol>, __strong id)' is not an Objective-C object`
So how can I include a C function or block reference in the dictionary? There will be quite a few larger complex functions to be defined, so it would be very much preferred to not have all of them defined inside the dictionary literal itself (a technique I know will work).
--
Also, I'm not sure what's considered proper style here: (1) I originally had the dictionary declaration outside of any method body at the file scope (without the dispatch_once(...)) which generates the same error, but I thought maybe it would be easier for others to see what's going on by (2) including it in the only method that uses that dictionary. Is one style preferred over the other for any reason?
Your Handler type is a block type, not a function pointer type. If you had declared it using * instead of ^, it would be a function pointer type.
Your myCommandHandler function is, of course, a function, not a block. Your comment is wrong. It does not match type Handler.
Function pointers are not Objective-C object pointers. Functions are not objects. Blocks are Objective-C objects, but you're not actually using any blocks here. (You've just declared a typedef for one, but you're not actually using it.)
You could use blocks and store them in your dictionary. The blocks could either contain the desired code or call a function or method which does.
A C function address is not an Objective-C object, and an NSDictionary can only store the latter.
A C function address is just a pointer, to wrap a C pointer as an object you use NSValue and its class method valueWithPointer.
To get the pointer value back from the NSValue object you use the instance method pointerValue. Before you can use the extracted pointer you must cast it to your function type.
HTH
I have used blocks a few times but never with declaring a typedef first.
I am trying to setup this definitions on a class (lets call it ClassA)
typedef void (^myBlock)();
#property (nonatomic, copy) myBlock onCompletion;
Then I create an instance of the object this class represents and do this:
ClassA *obj = [[ClassA alloc] init];
obj.onCompletion = ^(){
// my code here
};
it is complaining "incompatible block pointer types assigning"...
can you guys explain?
Although you don't have to specify the return type of a block, you must specify void if your block doesn't take any parameters.
Check out this link for block reference: block syntax
Just guessing it might be because you left the block parameter type blank.
typedef void (^myBlock)(void); //Untested
At the request of the OP I am posting my original comment as an answer even though there are other answers stating the same thing:
You need to clearly specify that the block takes no parameters. Your typedef should be:
typedef void (^myBlock)(void);
The only difference in the declared block type myBlock and the type of the block literal might be the return type.
If you leave the return type out in a block literal the compiler figures it out automatically:
myBlock block1 = ^() { // everything is fine
return;
};
myBlock block2 = ^() { // does not work, types differ
return 1;
};
I am using a third-party library that requires a C callback in an iOS program. The callback provides a void* userdata parameter that I can use as I wish. In this callback I want to create an NSData object that is returned to the code that invokes the API that eventually calls the callback. For example:
// C callback:
static void callback(int x, void* userdata)
{
if (userdata)
{
// This gives an error:
// Pointer to non-const type 'NSData*' with no explicit ownership
NSData** p = (NSData**)userdata;
*p = [NSData init:...];
}
}
// main code:
NSData* d = ...; // sometimes valid, sometimes nil
library_api(callback, &d); // have the callback initialize or replace d
if (d)
{
[d doSomthing:...];
}
I am using ARC, which I think is at the root of the issues. I thought of using a struct to hold the NSData*, but ARC forbids Objective-C objects in structs or unions. There is probably some variant of __bridge that might help, but I am not sure which. I have looked at a lot of SO questions and read the Apple docs, but it is not clear to me how to code this up.
Ideally, if d were not nil at the time the callback is invoked, its current value would be released and a new NSData object would replace it. In other words, when library_api completes, d always holds the NSData object created by the callback, and any previously held value would have been released properly.
I suppose I could keep the Objective-C code out of the callback and just malloc() a buffer to store the data which would then be copied to an NSData object in the main code, but I am hoping that I can avoid that extra step.
You can't transfer object ownership to a void*, but you can transfer object ownership to a CoreFoundation type, like CFDataRef or CFTypeRef. You're then free to pass around the CF pointer as you wish.
e.g.:
NSData* data = ...
CFTypeRef cfData = (__bridge CFTypeRef)data; // If you want to pass in data as well.
library_api(callback, &cfData);
if (cfData)
{
data = (__bridge_transfer NSData*)cfData; // Transfer ownership to ARC. No need to call CFRelease(cfData).
NSLog#("Data: %#", data);
}
And in the callback:
static void callback(int x, void* userdata)
{
if (userdata)
{
CFTypeRef* cfDataPtr = userdata;
CFTypeRef cfInData = *cfDataPtr;
NSData* inData = (__bridge NSData*)cfInData;
NSLog(#"In Data: %#", inData);
NSData* outData = [[NSData alloc] init];
CFTypeRef cfOutData = (__bridge_retained CFTypeRef)outData; // Transfer ownership out of ARC.
*cfDataPtr = cfOutData;
}
}
You can have struct contain ObjC object, they just have to be __unretained_unsafe OR in .mm file.
There are few options:
1 Use a struct to hold ObjC object in .m file
struct MyStruct
{
__unretained_unsafe id obj;
}
2 Use a struct to hold ObjC object in .mm file (Objective-C++) and use C++ new/delete for the struct. You can do this because compiler will generate retain/release in the constructor/destructor of the struct.
struct MyStruct
{
id obj; // no need to have __unretained_unsafe
}
3 Change the signature of the callback function and cast it (I didn't try this before)
4 Just make this file non ARC with -fno-objc-arc compiler flag
typedef void (^RequestProductsCompletionHandler)(BOOL success, NSArray * products);
I am having difficulty understanding what this line of code is doing in .h file.
Please explain in detail
typedef.
void (I know what void do, but whats the purpose here?).
(^RequestProductsCompletionHandler)(BOOL success, NSArray * products);
How to call it?
This is definition of objective-c block type with name RequestProductsCompletionHandler that takes 2 parameters (BOOL and NSArray) and does not have return value. You can call it the same way you would call c function, e.g.:
RequestProductsCompletionHandler handler = ^(BOOL success, NSArray * products){
if (success){
// Process results
}
else{
// Handle error
}
}
...
handler(YES, array);
Vladimir described it well. It defines a variable type which will represent a block that will pass two parameters, a boolean success and an array of products, but the block itself returns void. While you don't need to use the typedef, it makes the method declaration a tad more elegant (and avoids your having to engage in the complicated syntax of block variables).
To give you a practical example, one might infer from the name of the block type and its parameters that this defines a completion block (e.g. a block of code to be performed when some asynchronous operation, like a slow network request, completes). See Using a Block as a Method Argument.
For example, imagine that you had some InventoryManager class from which you could request product information, with a method with an interface defined like so, using your typedef:
- (void)requestProductsWithName:(NSString *)name completion:(RequestProductsCompletionHandler)completion;
And you might use the method like so:
[inventoryManager requestProductsWithName:name completion:^(BOOL success, NSArray * products) {
// when the request completes asynchronously (likely taking a bit of time), this is
// how we want to handle the response when it eventually comes in.
for (Product *product in products) {
NSLog(#"name = %#; qty = %#", product.name, product.quantity);
}
}];
// but this method carries on here while requestProductsWithName runs asynchronously
And, if you looked at the implementation of requestProductsWithName, it could conceivably look something like:
- (void)requestProductsWithName:(NSString *)name completion:(RequestProductsCompletionHandler)completion
{
// initiate some asynchronous request, e.g.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// now do some time consuming network request to get the products here
// when all done, we'll dispatch this back to the caller
dispatch_async(dispatch_get_main_queue(), {
if (products)
completion(YES, products); // success = YES, and return the array of products
else
completion(NO, nil); // success = NO, but no products to pass back
});
});
}
Clearly, this is unlikely to be precisely what your particular completion handler block is doing, but hopefully it illustrates the concept.
Mike Walker created a nice one page site that shows all possibilities to declare a block in Objective-C. This can be helpful to understand your problem as well:
http://fuckingblocksyntax.com
To quote his site, this is how you can define blocks:
As a local variable:
returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};
As a property:
#property (nonatomic, copy) returnType (^blockName)(parameterTypes);
As a method parameter:
- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName {...}
As an argument to a method call:
[someObject someMethodThatTakesABlock: ^returnType (parameters) {...}];
As a typedef:
typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^(parameters) {...}
I want to call a c function from objective-c and pass objective-c function as a callback
the problem is this function has a callback as parameter, so I have to pass objective-c function as a call back to c function
here is the header of the c function
struct mg_context *mg_start(const struct mg_callbacks *callbacks,
void *user_data,
const char **configuration_options);
here is where I try to call it
- (void)serverstarted
{
NSLog(#"server started");
}
- (IBAction)startserver:(id)sender {
NSLog(#"server should start");
const char *options[] =
{
"document_root", "www",
"listening_ports", "8080",
NULL
};
mg_start(serverstarted(), NULL, options);
}
I have tried several ways to do it and searched the web to just get a clue how to do it but with not luck
here is the library I am incuding in my code
https://github.com/valenok/mongoose
Your chief problem is the first parameter to mg_start(), which is described in the declaration as const struct mg_callbacks *callbacks. You are trying pass a pointer to a function. (Actually you are trying to pass the result of a call to that function, which is even further from the mark.) That isn't what it says: it says a pointer to a struct (in particular, an mg_callbacks struct).
The example code at https://github.com/valenok/mongoose/blob/master/examples/hello.c shows you how to configure this struct. You have to create the struct and put the pointer to the callback function inside it. Then you pass the address of that struct.
Other problems with your code: your callback function itself is all wrong:
- (void)serverstarted
{
NSLog(#"server started");
}
What's wanted here is a C function declared like this: int begin_request_handler(struct mg_connection *conn), that is, it takes as parameter a pointer to an mg_connection struct. Your serverstarted not only doesn't take that parameter, it isn't even a C function! It's an Objective-C method, a totally different animal. Your use of the term "Objective-C function" in your title and your question is misleading; C has functions, Objective-C has methods. No Objective-C is going to be used in the code you'll be writing here.
What I suggest you do here is to copy the hello.c example slavishly at first. Then modify the content / names of things slowly and bit by bit to evolve it to your own code. Of course learning C would also help, but you can probably get by just by copying carefully.
As matt already said, you cannot pass an Objective-C method as callback where a C function
is expected. Objective-C methods are special functions, in particular the receiver ("self")
is implicitly passed as first argument to the function.
Therefore, to use an Objective-C method as request handler, you need an (intermediate) C function as handler and you have to pass self to that function, using the user_data argument. The C function can then call the Objective-C method:
// This is the Objective-C request handler method:
- (int)beginRequest:(struct mg_connection *)conn
{
// Your request handler ...
return 1;
}
// This is the intermediate C function:
static int begin_request_handler(struct mg_connection *conn) {
const struct mg_request_info *request_info = mg_get_request_info(conn);
// Cast the "user_data" back to an instance pointer of your class:
YourClass *mySelf = (__bridge YourClass *)request_info->user_data;
// Call instance method:
return [mySelf beginRequest:conn];
}
- (IBAction)startserver:(id)sender
{
struct mg_callbacks callbacks;
memset(&callbacks, 0, sizeof(callbacks));
callbacks.begin_request = begin_request_handler;
const char *options[] =
{
"document_root", "www",
"listening_ports", "8080",
NULL
};
// Pass "self" as "user_data" argument:
mg_start(&callbacks, (__bridge void *)self, options);
}
Remarks:
If you don't use ARC (automatic reference counting) then you can omit the (__bridge ...)
casts.
You must ensure that the instance of your class ("self")
is not deallocated while the server is running. Otherwise the YourClass *mySelf
would be invalid when the request handler is called.