Search code examples
swiftswift2

calling a function defined in assembly from swift


I know in swift it is possible to interop with c using the @_silgen_name attr on a function in a swift module. Is there a way to do this with a symbol defined in an assembly file? I would like to make syscalls using Swift. This is why I'm asking.


Solution

  • You can use Objective-C to create a bridging-header (usually named something like MyProject-Bridging-Header.h) that contains the function prototype. Bridging-headers allow Swift to access Objective-C (and by extension, C or assembly). They are well documented.

    You can also use Swift's @_silgen_name attribute to achieve the same effect. However, this is not properly supported.

    For example, given your assembly code:

    .globl _add // ensure that the symbol can be found
    
    ...
    
    _add: // int add(int a, int b)
        movl %esi, %eax
        addl %edi, %eax
        ret
    

    You would put the prototype in a bridging-header (this is the recommended way to do it):

    int add(int a, int b);
    

    Alternatively, you can do something like this at the top-level of your Swift module (however, this is unofficial, and is not future-proof):

    @_silgen_name("add") func add(a: Int32, b: Int32) -> Int32
    

    Either way, you can then invoke the function in Swift like any other function:

    let a = add(1, 2);