1

I get the following error for the code below: "A C function pointer cannot be formed from a local function that captures context."

Does anyone propose a creative solution to populate x in this example? I'm stumped. The underlying types for _header and _int respectively are UnsafePointer<mach_header>? and Int

import MachO
class Example {
    func test() {
        var x: [Int] = []
        _dyld_register_func_for_add_image { (_header, _int) in
            x.append(_int)
        }
    }
}
Grant Park
  • 1,004
  • 1
  • 9
  • 29
  • That code compiles without problems for me. – Martin R Jan 15 '17 at 00:29
  • How about in the case `x` is not a static variable? – Grant Park Jan 15 '17 at 00:33
  • That wouldn't work. `_dyld_register_func_for_add_image` takes a C function as argument. In Swift that are global functions or closure that capture no context. *If* there were a user pointer parameter then you could use a technique as in http://stackoverflow.com/a/33262376/1187415, but such a parameter is not available here – Martin R Jan 15 '17 at 00:39

1 Answers1

2

You could make x a static variable so it is accessible from anywhere and not depending on context. But it depends on your use case whether this works.

silicon_valley
  • 2,639
  • 2
  • 16
  • 20