Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call C from Swift?

Tags:

c

swift

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 to be able to call the objc runtime libraries from swift.

In particular, how do you bridge iOS C headers?

like image 812
Blaze Avatar asked Jun 02 '14 23:06

Blaze


People also ask

Can you use C on iOS?

Unlike Android which needs a special API (the NDK) to support native development, iOS supports it by default. C or C++ development is more straightforward with iOS because of a feature called 'Objective-C++'.

Can you mix Objective-C and Swift?

You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.

Is Objective-C same as Swift?

Swift is easier to read and easier to learn than Objective-C. Objective-C is over thirty years old, and that means it has a more clunky syntax. Swift streamlines code and more closely resembles readable English, similar to languages like C#, C++, JavaScript, Java, and Python.


2 Answers

Yes, you can of course interact with Apple's C libraries. Here is explained how.

Basically, the C types, C pointers, etc., are translated into Swift objects, for example a C int in Swift is a CInt.

I've built a tiny example, for another question, which can be used as a little explanation, on how to bridge between C and Swift:

main.swift

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

UserInput.c

#include <stdio.h>  void getInput(int *output) {     scanf("%i", output); } 

cliinput-Bridging-Header.h

void getInput(int *output); 

Here is the original answer.

like image 121
Leandros Avatar answered Oct 05 '22 23:10

Leandros


The compiler converts C API to Swift just like it does for Objective-C.

import Cocoa  let frame = CGRect(x: 10, y: 10, width: 100, height: 100)  import Darwin  for _ in 1..10 {     println(rand() % 100) } 

See Interacting with Objective-C APIs in the docs.

like image 21
rickster Avatar answered Oct 05 '22 23:10

rickster