That's… what withUnsafePointer(to:)
does: it yields a (generally temporary) pointer to the value passed to it that is valid for the lifetime of the closure that was also passed to it.
I'm not sure what "they" refers to here.
The type of DllMain
in Swift is something like @convention(c) (HINSTANCE, DWORD, LPVOID) -> BOOL
(ignoring __stdcall
which we can't currently represent in Swift.) The value of DllMain
, in Swift, is the address of the first instruction in the function, i.e. it's a function pointer. Copying DllMain
simply means making another scalar value with the same bit pattern (at least on architectures we generally deal with—technically, function pointers need not be scalar, but that's not interesting right now.)
I think some of the confusion here stems from the fact that, in C and C++, the following two expressions are equivalent:
auto p1 = &DllMain;
auto p2 = DllMain;
The original syntax in C for getting a pointer to a function was p1
, and p2
was simply invalid or nonsensical. C++ and later C compilers like GCC/clang accept p2
as equivalent to p1
. In other words, &someFunctionName
and someFunctionName
are equivalent in C.
Swift doesn't let you form a pointer or reference to an immutable value (such as a declared function) using &
, but in general withUnsafePointer(to:)
and &
serve the same purpose. Except that for function types, they don't behave the same way because Swift doesn't have the same magic syntactic sugar that C/C++ have for function pointers.
When you write withUnsafePointer(to: DllMain) { p in ... }
, the value of p
is some address that points to DllMain
, but DllMain
is, to Swift, the address of the function's first instruction, not the body of the function itself. So p
is a pointer to the function pointer.
@compnerd and I chatted off-forum briefly and confirmed that he's using it something like:
let untypedFunctionPointer = withUnsafePointer(to: DllMain) { p in
p.withMemoryRebound(to: UnsafeRawPointer.self) { p2 in
p2.pointee
}
}
Which is a long way of writing unsafeBitCast(DllMain, to: UnsafeRawPointer.self)
.