有没有办法将Objectivec块包裹到功能指针中



我必须在iOS应用中为特定的C库提供C风格回调。回调没有void *userData或类似的内容。因此,我无法在某种程度上循环。我想避免引入全球环境来解决这个问题。理想的解决方案将是一个目标-C块。

我的问题:有没有办法将块"铸造"到功能指针中或以某种方式包裹/掩盖它?

从技术上讲,您可以访问该块的功能指针。但是这样做是完全不安全的,所以我当然不建议这样做。要查看如何考虑以下示例:

#import <Foundation/Foundation.h>
struct Block_layout {
    void *isa;
    int flags;
    int reserved; 
    void (*invoke)(void *, ...);
    struct Block_descriptor *descriptor;
};
int main(int argc, char *argv[]) {
    @autoreleasepool {
        // Block that doesn't take or return anything
        void(^block)() = ^{
            NSLog(@"Howdy %i", argc);
        };
        // Cast to a struct with the same memory layout
        struct Block_layout *blockStr = (struct Block_layout *)(__bridge void *)block;
        // Now do same as `block()':
        blockStr->invoke(blockStr);


        // Block that takes an int and returns an int
        int(^returnBlock)(int) = ^int(int a){
            return a;
        };
        // Cast to a struct with the same memory layout
        struct Block_layout *blockStr2 = (struct Block_layout *)(__bridge void *)returnBlock;
        // Now do same as `returnBlock(argc)':
        int ret = ((int(*)(void*, int a, ...))(blockStr2->invoke))(blockStr2, argc);
        NSLog(@"ret = %i", ret);
    }
}

跑步的运行:

Howdy 1
ret = 1

这是我们直接使用block()直接执行这些块的期望。因此,您可以将invoke用作功能指针。

,但是正如我所说,这完全不安全。实际上不要使用此!

如果您想查看某种方法来做您要问的事情,请检查一下:http://www.mikeash.com/pyblog/friday-qa-2010-02-12-trampolining-blocks-with-mutable-code.html

这只是您需要做的事情才能使它起作用。可悲的是,它永远不会在iOS上使用(因为您需要将页面标记为可执行文件,而该页面不允许在应用程序的沙箱中执行)。但是,尽管如此,一篇很棒的文章。

如果您的块需要上下文信息,并且回调不提供任何上下文,恐怕答案是清楚的。块必须在某个地方存储上下文信息,因此您将永远无法将这样的块施放到无arguments函数指针中。

在这种情况下,经过精心设计的全局变量方法可能是最好的解决方案。

mablockclosusion可以正是这样做的。但对于您需要的一切可能都是过分的。

我知道这已经解决了,但是对于有兴趣的各方,我还有另一个解决方案。

将整个功能重新映射到新的地址空间。新的结果地址可以用作所需数据的关键。

#import <mach/mach_init.h>
#import <mach/vm_map.h>
void *remap_address(void* address, int page_count)
{
    vm_address_t source_address = (vm_address_t) address;
    vm_address_t source_page = source_address & ~PAGE_MASK;
    vm_address_t destination_page = 0;
    vm_prot_t cur_prot;
    vm_prot_t max_prot;
    kern_return_t status = vm_remap(mach_task_self(),
                                &destination_page,
                                PAGE_SIZE*(page_count ? page_count : 4),
                                0,
                                VM_FLAGS_ANYWHERE,
                                mach_task_self(),
                                source_page,
                                FALSE,
                                &cur_prot,
                                &max_prot,
                                VM_INHERIT_NONE);
    if (status != KERN_SUCCESS)
    {
        return NULL;
    }
    vm_address_t destination_address = destination_page | (source_address & PAGE_MASK);
    return (void*) destination_address;
}

记住处理不再需要的页面,并注意,每个调用比Mablockclosusy需要更多的内存。

(在iOS上测试)

最新更新