-
-
Notifications
You must be signed in to change notification settings - Fork 458
/
Copy pathcgo.go
79 lines (66 loc) · 1.02 KB
/
cgo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
/*
#include <stdio.h>
#include <stdlib.h>
void print(char* s) {
printf("%s", s);
}
long factorial(int n) {
if (n == 0) {
return 1;
} else {
return (n * factorial(n - 1));
}
}
long gcd(long a, long b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
void prime(int n) {
int i = 0, count, c;
for (count = 2; count <= n + 1; ) {
for (c = 2; c <= i - 1; c++ ) {
if (i % c == 0) {
break;
}
}
if (c == i) {
printf("%d ", i);
count++;
}
i++;
}
print("\n");
}
int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return (fibonacci(n - 1) + fibonacci(n - 2));
}
}
*/
import "C"
import (
"fmt"
"unsafe"
)
func main() {
fmt.Print("C.print: ")
cs := C.CString("Hello from cgo\n")
C.print(cs)
C.free(unsafe.Pointer(cs))
fmt.Print("C.factorial: ")
fmt.Println(C.factorial(5))
fmt.Print("C.gcd: ")
fmt.Println(C.gcd(15, 230))
fmt.Print("C.prime: ")
C.prime(6)
fmt.Print("C.fibonacci: ")
fmt.Println(C.fibonacci(5))
}