How to call C from Swift?

前端 未结 6 1592
夕颜
夕颜 2020-11-27 10:33

Is there a way to call C routines from Swift?

A lot of iOS / Apple libraries are C only and I\'d still like to be able to call those.

For example, I\'d like

6条回答
  •  庸人自扰
    2020-11-27 10:42

    In the case of c++, there is this error that pops up:

      "_getInput", referenced from: 
    

    You need a c++ header file too. Add c-linkage to your function, then include the header file in the bridge-header:

    Swift 3

    UserInput.h

    #ifndef USERINPUT_H
    #define USERINPUT_H    
    
    #ifdef __cplusplus
    extern "C"{
    #endif
    
    getInput(int *output);
    
    #ifdef __cplusplus
    }
    #endif
    

    UserInput.c

    #include 
    
    void getInput(int *output) {
        scanf("%i", output);
    }    
    

    main.swift

    import Foundation
    var output: CInt = 0
    getInput(&output)
    print(output)
    

    cliinput-Bridging-Header.h

    #include "UserInput.h"
    

    Here is the original video explaining this

提交回复
热议问题