package main
/*
#include <stdlib.h> // Include the C standard library for memory management functions
*/
import "C" // Import the C language features for interoperability
import "unsafe" // Import unsafe for pointer manipulation
// Fibonacci computes the first n Fibonacci numbers and returns a pointer to an array of integers.
// It takes an integer n (C.int) as an argument, which represents how many Fibonacci numbers to compute.
//
//export Fibonacci
func Fibonacci(n C.int) *C.int {
// Allocate memory for the result array in C
// Using C.malloc to allocate memory for an array of integers (size of n).
result := C.malloc(C.size_t(n) * C.size_t(unsafe.Sizeof(C.int(0))))
// Typecast the result pointer to a Go slice to populate it.
// The slice will allow us to easily access and modify the allocated memory.
resultSlice := (*[1 << 30]C.int)(result)[:n:n] // Create a slice of C.int from the allocated memory
// Initialize the first two Fibonacci numbers
if n > 0 {
resultSlice[0] = 0 // First Fibonacci number
}
if n > 1 {
resultSlice[1] = 1 // Second Fibonacci number
}
// Compute the Fibonacci sequence from the third number onward
for i := 2; i < int(n); i++ {
resultSlice[i] = resultSlice[i-1] + resultSlice[i-2] // F(n) = F(n-1) + F(n-2)
}
// Print a message indicating that the Go code is running
print("You're running the Go code\\n")
// Return a pointer to the allocated C array containing Fibonacci numbers
return (*C.int)(result)
}
// The main function is not needed for the library
// It is left empty to comply with the requirements of cgo, which needs a main function
// if the file is compiled into an executable, but here it will be built as a shared library.
func main() {}
go build -buildmode=c-archive -o libfibonacci.a .
This will give you libfibonacci.h and libfibonacci.a files.
#include "libfibonacci.h"
$(PROJECT_DIR)/GoWrapperMacApp/GoWrapperMacApp-Bridging-Header.h