Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift and Objective-C / C Interoperability

Swift and Objective-C / C Interoperability

Swift was designed from the start to coexist with existing ecosystems, so calling Objective-C and C code is almost zero-cost.

The reverse direction works too: add @objc to Swift members, and Objective-C can call them just like native classes.

Interoperability with C++ came later; it requires explicitly enabling interop mode and has clear limitations.

This article walks through all three boundaries from two directions: "Swift calling the other side" and "the other side calling Swift".


Three Interoperability Boundaries

First, an overview: the three boundaries differ in how they are enabled and in their limitations.

Direction How to Enable Main Limitations
Swift calling Objective-C Bridging header or module map Requires the Objective-C runtime, mainly on Apple platforms
Objective-C calling Swift Add @objc to Swift members and import the generated -Swift.h Member types must be representable as Objective-C types
Swift calling C Bridging header or module map Requires manual management of pointer lifetimes
C calling Swift Export with @_cdecl Parameters and return values must be C-compatible types
Swift and C++ interoperability Enable -cxx-interoperability-mode Does not support C++ exceptions or virtual function inheritance

A bridging header is for app targets, while a module map is for frameworks and packages.


Swift calling Objective-C

When you first add an Objective-C file to an Xcode project, Xcode proactively asks whether to create a bridging header.

You can also manually specify a header path in Build Settings under Objective-C Bridging Header.

Objective-C headers #imported in the bridging header can be used directly in Swift code without another import.

Example

// File path: RunoobGreeter.h

#import

NS_ASSUME_NONNULL_BEGIN

@interface RunoobGreeter

:

NSObject

@property

(

nonatomic, copy

)

NSString

site

;

(

NSString

)

greet

;

@end

NS_ASSUME_NONNULL_END

Example

// File path: RunoobGreeter.m

#import "RunoobGreeter.h"

@implementation RunoobGreeter

(

instancetype

)

init

{

    self

=

[

super init

]

;

   

if

(

self

)

{

_site

=

@

"www.runoob.com"

;

}

   

return

self

;

}

(

NSString

)

greet

{

   

return

[

NSString stringWithFormat

:

@

"Hello, %@"

, self.

site

]

;

}

@end

Example

// File path: app.swift

import Foundation

// The bridging header lets Swift see Objective-C classes directly

let greeter

=

RunoobGreeter

(

)

greeter.

site

=

"RUNOOB"

print

(

greeter.

greet

(

)

)



Hello, RUNOOB

When verifying from the command line, the corresponding parameter is -import-objc-header.



$ swiftc -swift-version 6 -import-objc-header RunoobGreeter.h \

    -o runoob_app app.swift RunoobGreeter.m -framework Foundation

$ ./runoob_app

Hello, RUNOOB

Important details:In the header file, the NS_ASSUME_NONNULL_BEGIN and NS_ASSUME_NONNULL_END cannot be omitted. Without it, Objective-C's NSString * is imported into Swift as String!and prints as Optional("Hello, RUNOOB")which can hide the risk of implicitly unwrapped crashes.


Objective-C calling Swift: @objc and -Swift.h

The compiler generates an Objective-C header for every module containing Swift code, named ModuleName-Swift.h.

In frameworks it is usually ProductName-Swift.h; with command-line builds it is determined by -module-name.

An Objective-C file only needs to #import "RunoobService-Swift.h" to use members marked @objc in Swift.

Example

// File path: RunoobService.swift

import Foundation

// @objcMembers: automatically adds @objc to all Objective-C-compatible members of the class

@objcMembers

public

class

RunoobService

:

NSObject

{

   

public

var site

:

String

=

"www.runoob.com"

   

public

func greet

(

_ name

:

String

)

String

{

       

"Hello, (name), welcome to (site)"

   

}

   

// Rename a Swift method to a specified Objective-C selector

    @objc

(

runoobVersion

)

   

public

func version

(

)

String

{

       

"RUNOOB-1.0"

   

}

}

Example

// File path: main.m

#import

#import "RunoobService-Swift.h"

int

main

(

void

)

{

    @autoreleasepool

{

        RunoobService

service

=

[

[

RunoobService alloc

]

init

]

;

        service.

site

=

@

"RUNOOB"

;

        NSLog

(

@

"%@"

,

[

service greet

:

@

"Runoob"

]

)

;

        NSLog

(

@

"%@"

,

[

service runoobVersion

]

)

;

   

}

   

return

0

;

}



$ ./runoob_objc_app

Hello, Runoob, welcome to RUNOOB

RUNOOB-1.0

In the generated header, the corresponding declaration looks like this.



@interface RunoobService : NSObject

@property (nonatomic, copy) NSString * _Nonnull site;

- (NSString * _Nonnull)greet:(NSString * _Nonnull)name SWIFT_WARN_UNUSED_RESULT;

- (NSString * _Nonnull)runoobVersion SWIFT_WARN_UNUSED_RESULT;

- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;

@end

Here is a particularly easy pitfall to fall into:The generated -Swift.h only includes public and open members。

Remove all the public modifiers above and you will find nothing in the header, and the Objective-C side will report an unknown receiver error.


@objc, @objcMembers, and dynamic

These three keywords often appear together, but they serve different purposes.

The keyword Purpose Typical scenario
@objc Expose a single member to Objective-C Precisely control which members can be called from Objective-C
@objcMembers Automatically add @objc to all compatible members of a class The whole class is to be used by Objective-C
dynamic Force dynamic dispatch instead of static or vtable dispatch Needed for runtime features such as KVO and method swizzling

@objc can be followed by parentheses specifying a selector name, which is how @objc(runoobVersion) is used in the earlier example.

When unspecified, Swift converts the method name to the corresponding Objective-C selector, and the mapping of parameter labels is handled by the compiler.

Using dynamic alone means "this member must be dispatched dynamically", while @objc dynamic means "dispatched dynamically through the Objective-C messaging mechanism", which is a prerequisite for KVO and swizzling.

Note:Marking @objc For members marked this way, parameter and return types must be representable as Objective-C types. For example, passing a Swift struct as a parameter causes the compiler to report an error: instance method cannot be marked '@objc' because the type of the parameter cannot be represented in Objective-C.


C Interoperability

Calling C from Swift works the same way as calling Objective-C, via a bridging header or module map.

Example

// File path: runoob.h

#ifndef RUNOOB_H

#define RUNOOB_H

int

runoob_add

(

int

a,

int

b

)

;

int

runoob_strlen

(

const

char

s

)

;

#endif

Example

// File path: app.swift

import Foundation

// Call C functions directly through the bridging header

print

(

runoob_add

(

20

,

22

)

)

print

(

runoob_strlen

(

"www.runoob.com"

)

)



$ swiftc -swift-version 6 -import-objc-header runoob.h -o runoob_app app.swift helper.c

$ ./runoob_app

42

14

In the reverse direction, exporting a Swift function for use by C requires @_cdecl with a specified C symbol name.

Example

// File path: lib.swift

import Foundation

// Export as a C symbol named runoob_add

@_cdecl

(

"runoob_add"

)

public

func runoobAdd

(

_ a

:

Int32, _ b

:

Int32

)

Int32

{

    a

b

}

// Receive a C string pointer

@_cdecl

(

"runoob_strlen"

)

public

func runoobStrlen

(

_ s

:

UnsafePointer

<

CChar

)

Int32

{

Int32

(

strlen

(

s

)

)

}

// File path: main.c

#include

#include "runoob.h"

int

main

(

void

)

{

   

printf

(

"%d\n"

, runoob_add

(

20

,

22

)

)

;

   

printf

(

"%d\n"

, runoob_strlen

(

"www.runoob.com"

)

)

;

   

return

0

;

}



$ swiftc -swift-version 6 -parse-as-library -o runoob_app main.c lib.swift

$ ./runoob_app

42

14

Note that -parse-as-library must not be omitted; otherwise Swift treats lib.swift as the main file, conflicting with the main function in main.c.

The core of C interoperability is the UnsafePointer family, whose members differ greatly in semantics.

Type Meaning Whether the pointed-to memory can be modified
UnsafePointer A read-only pointer to a single value No
UnsafeMutablePointer A writable pointer to a single value Is
UnsafeBufferPointer A read-only buffer over a contiguous region of memory No
UnsafeMutableBufferPointer A writable buffer over a contiguous region of memory Is
UnsafeRawPointer A raw pointer without type information No

Do not hold on to these pointers yourself; instead use the withUnsafe... family of functions and use them temporarily inside a closure.

Example

import Foundation

// withUnsafePointer: temporarily obtain the memory address of a value

var value

=

42

withUnsafePointer

(

to

:

&

value

)

{

ptr in

    print

(

"Address is readable, value is (ptr.pointee)"

)

}

// withContiguousStorageIfAvailable: temporarily expose a string's UTF-8 bytes as a buffer

let site

=

"RUNOOB"

let count

=

site.

utf8

.

withContiguousStorageIfAvailable

{

buffer

Int in

    buffer.

count

}

print

(

"Byte count: (count ?? -1)"

)

// withUnsafeBufferPointer: directly iterate over an array's underlying buffer

let numbers

=

[

10

,

20

,

30

]

let sum

=

numbers.

withUnsafeBufferPointer

{

buffer

Int in

    var total

=

0

   

for

i in

0

..

<

buffer.

count

{

        total

=

buffer

[

i

]

   

}

   

return

total

}

print

(

"Sum: (sum)"

)



地址可读,值为 42

字节数:6

总和:60

These functions guarantee that a pointer is valid only while the closure is executing and should not be used after it exits, minimizing the risk of dangling pointers.


Interoperability with C++

Starting with Swift 5.9, you can call C++ code directly by enabling the interop mode -cxx-interoperability-mode.

C++ types are exposed to Swift through a module map, written similarly to a C module map but requiring requires cplusplus.

Example

// File path: RunoobMath.hpp

#pragma once

struct

RunoobCounter

{

   

int

value

=

0

;

   

void

add

(

int

n

)

{

value

=

n

;

}

   

int

get

(

)

const

{

return

value

;

}

}

;

inline

int

runoobPort

(

)

{

return

8080

;

}

Example

// File path: module.modulemap

module RunoobMath

{

    header

"RunoobMath.hpp"

    requires cplusplus

}

Example

// File path: app.swift

import Foundation

import RunoobMath

// A C++ struct appears in Swift as a value type

var counter

=

RunoobCounter

(

)

counter.

add

(

40

)

counter.

add

(

2

)

print

(

counter.

get

(

)

)

print

(

runoobPort

(

)

)



$ swiftc -swift-version 6 -cxx-interoperability-mode=default -I . -o runoob_cxx_app app.swift

$ ./runoob_cxx_app

42

8080

This interoperability is powerful, but its boundaries are clear: two things cannot be done.

First, C++ exceptions are not supported. A C++ function that may throw appears in Swift as an ordinary function; once an exception crosses the boundary, the runtime terminates the program.



$ ./eapp

C++ exception handling detected but the Swift runtime was compiled with exceptions disabled

Second, inheriting from C++ classes and overriding virtual functions are not supported; Swift cannot treat a C++ class as a superclass.



error: inheritance from non-protocol, non-class type 'RunoobBase'

Therefore C++ interoperability is better suited to "calling stateless or value-semantic utility code" than to moving an entire C++ class hierarchy into Swift.


Common questions

Why can't the Objective-C side find my Swift class?

First confirm whether the class is marked with @objc or @objcMembers.

Then confirm that the class and its members are public or open, since the generated -Swift.h only includes members at these two levels.

How to choose between a bridging header and a module map

Use a bridging header for app targets and specify the path in Build Settings.

Use a module map for frameworks, libraries, and Swift packages, because such artifacts need to export C headers as part of the module.

Does @objc cause a performance penalty?

Slightly, because calls go through Objective-C message dispatch rather than Swift's static dispatch.

Only add it when you genuinely need Objective-C access or runtime features, and don't add @objcMembers to an entire class indiscriminately.

Can the pointer returned by withUnsafePointer be saved for later use?

No. It is valid only while the closure is executing; once the closure returns, the pointer is invalid.

When you need to hold memory long-term, allocate it manually with UnsafeMutablePointer.allocate and take responsibility for freeing it.

Does C++ interoperability require changing C++ code?

In most cases no, as long as the header can be parsed by Clang.

But when features such as templates, exceptions, or multiple inheritance are involved, the compiler may skip or simplify these declarations, so each needs verification.