Alejandro
(Alejandro Alonso)
1
I have a pointer to some swift function and I'd like to be able to bitcast it and call it. The issue arises from the fact that when I do:
unsafeBitCast(ptr, to: (() -> ()).self)
it's actually bitcasting to a closure object which doesn't have the same layout size as a pointer (closures are two words vs. a pointer is just a single word), which ensues runtime crashes. Is this currently possible?
Joe_Groff
(Joe Groff)
2
There isn't any way to bitcast a pointer into a Swift function value. If you can make it so that the pointer uses the C calling convention, can you cast to a @convention(c) type instead?
Alejandro
(Alejandro Alonso)
3
Trying to bitcast a metadata accessor in Swift (can't change the cc of that!)
Joe_Groff
(Joe Groff)
4
What are you trying to do?
Alejandro
(Alejandro Alonso)
5
I'm trying to create a wrapper over this function pointer.
public struct MetadataAccessFunction {
public let ptr: UnsafeRawPointer
// this could be an interesting application for callAsFunction
public func call0(request: MetadataRequest) -> MetadataResponse {
let fn = unsafeBitCast(
ptr,
to: ((MetadataRequest) -> MetadataResponse).self
)
return fn(request)
}
// and so on for the number of generic args
}
Joe_Groff
(Joe Groff)
6
Unofficially, you might be able to get @convention(thin) to do the right thing. Aside from the weird calling convention, though, metadata accessor functions are also signed differently in arm64e, so it's going to be difficult to call them from Swift generally.
Alejandro
(Alejandro Alonso)
7
I see. Thin doesn't work (runtime crash), but I didn't know they were difficult to call from Swift. Thanks for the help.
Joe_Groff
(Joe Groff)
8
Maybe you can wrap up the ArrayRef version of MetadataAccessFunction::operator() from the runtime C++ code in a C-callable wrapper function which you could then use from swift.