Bitcast pointer to Swift function?

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?

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?

Trying to bitcast a metadata accessor in Swift (can't change the cc of that!)

What are you trying to do?

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(
      to: ((MetadataRequest) -> MetadataResponse).self

    return fn(request)

  // and so on for the number of generic args

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.

I see. Thin doesn't work (runtime crash), but I didn't know they were difficult to call from Swift. Thanks for the help.

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.