Calling Swift runtime methods

Out of curiosity, is there a way to call Swift runtime methods from Swift (for example - swift_conformsToProtocol or swift_retain), similar to how we can call objc runtime methods, such as objc_loadWeak?

I’m not at a computer right now, but you can just slap a @_silgen_name("swift_conformsToProtocol") on a function prototype. Although you probably want to figure out what the expecting method signature is as well.

Off the top of my head for example (probably wrong but remember this is off the top of my head)...

@_silgen_name("swift_getObjectType")
func getObjectType(of class: AnyObject) -> Any.Type

(Will comment more once I reach a computer)

Essentially any symbol exported can be called. You can find a list of symbols that the runtime and stdlib export with nm -gU /path/to/libswiftCore.dylib (I find myself doing this often because it’s fun to call internal stdlib functions :sweat_smile:)

3 Likes

Only if the runtime function in question uses the Swift calling convention. Calling runtime functions directly from Swift is not recommended, since LLVM optimization passes may make assumptions that they're used in specific ways by compiler-generated code that aren't followed by ad-hoc manual invocation.

4 Likes

I suppose you can turn off the optimisations by passing -Onone and/or --disable-llvm-optzns?