Skip to content

Commit 0962d7f

Browse files
committed
example C extension
0 parents  commit 0962d7f

File tree

4 files changed

+61
-0
lines changed

4 files changed

+61
-0
lines changed

Package.swift

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import PackageDescription
2+
3+
let package = Package(
4+
name: "Clibadder",
5+
targets: [
6+
Target(name: "Clibadder", dependencies: ["libadder"])
7+
]
8+
)

Sources/Clibadder/Clibadder.swift

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import libadder
2+
protocol Addable {
3+
func add(_ x: Int, _ y: Int) -> Int
4+
}
5+
6+
public struct SimpleAdd: Addable {
7+
func add(_ x: Int, _ y: Int) -> Int {
8+
return libadder.add(x, y)
9+
}
10+
}
11+
12+
public struct StructAdd: Addable {
13+
func add(_ x: Int, _ y: Int) -> Int {
14+
let op = add_operation(x: x, y: y, result: 0)
15+
let result = libadder.added(op)
16+
return result.result;
17+
}
18+
}
19+
20+
public struct PointerAdd: Addable {
21+
func add(_ x: Int, _ y: Int) -> Int {
22+
var op = add_operation(x: x, y: y, result: 0)
23+
libadder.adding(&op)
24+
return op.result;
25+
}
26+
}

Sources/libadder/include/libadder.h

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// our struct to hold values
2+
typedef struct {
3+
long x;
4+
long y;
5+
long result;
6+
} add_operation;
7+
8+
// simple add method
9+
long add(long x, long y);
10+
// struct by value
11+
add_operation added(add_operation op);
12+
// pointer to struct
13+
void adding(add_operation *op);

Sources/libadder/libadder.c

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#import "include/libadder.h"
2+
3+
long add(long x, long y) {
4+
return x + y;
5+
}
6+
7+
add_operation added(add_operation op) {
8+
add_operation result = {op.x, op.y, add(op.x, op.y)};
9+
return result;
10+
}
11+
12+
void adding(add_operation *op) {
13+
op->result = add(op->x, op->y);
14+
}

0 commit comments

Comments
 (0)