Also, in the first case the UnsafePointer points to local memory that
holds the function value. In the second case, you’re trying to load a
function value from the address of the function body.
Beginning to see...
I feel like there’s still one last piece missing here, which is that in
Swft a "function-typed value” is not the same as a “function pointer” in C.
Because a function value might have come from a closure, it might include
captured state…so the representation of a closure is not the same as a
representation of a plain function.
Because of *that*, the address you’re seeing isn’t the address of the
function in memory; it’s the address of the temporary allocation used to
represent “this global function and no associated state”. That’s why you
can’t just form a pointer with that bit-pattern and expect it to work.
Seeing!
Hope you’ve gotten some useful information between the three of us. :-)
That's the trifecta of support right there! Thank you all!
I ran a new little experiment for the curious:
var a: () -> () = {
print("foo!")
}
withUnsafePointer(&a) {$0}
$R0: UnsafePointer<() -> ()> = 0x00007fff5fbffce8
UnsafePointer<() -> ()>(bitPattern: 0x00007fff5fbffce8)!.pointee()
// foo!
UnsafePointer<() -> ()>(bitPattern: 0x0000000100561080)!.pointee()
// Crashes as expected!
And:
typealias MyType = @convention(c) () -> ()
var b: MyType = {
print("bar!")
}
b: __lldb_expr_10.MyType = 0x000000010056b150 $<snip> at repl12.swift
withUnsafePointer(&b) {$0}
$R1: UnsafePointer<__lldb_expr_10.MyType> = 0x0000000100564c80
UnsafePointer<MyType>(bitPattern: 0x0000000100564c80)!.pointee()
// bar!
UnsafePointer<MyType>(bitPattern: 0x000000010056b150)!.pointee()
// Crash!
I am surprised to find here that the addresses are different, albeit much
closer in space than the first example. I suppose there's still some swift
machinery at work to make a function type declared as @convention(c) to
_behave_ as a function pointer. Cool.
Thanks again Quinn, Andy, Jordan!
···
On Thu, Sep 1, 2016 at 1:48 PM, Andrew Trick <atrick@apple.com> wrote:
On Fri, Sep 2, 2016 at 9:49 AM, Jordan Rose <jordan_rose@apple.com> wrote:
a: () -> () = 0x0000000100561080 $<snip> at repl2.swift