libgofact
This project shows a simple C++ code to compute the factorial of n, and how it can be called from Go Go (golang) using SWIG
Factorial example
For this example, we'll use fact.h, fact.cpp, and fact.i.
File fact.h
#ifndef FACTORIAL_H
#define FACTORIAL_H
unsigned long long factorial(int n);
#endif
File fact.cpp
#include "fact.h"
unsigned long long factorial(int n) {
unsigned long long result = 1;
for(int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
File fact.i
%module libfact
%{
#include "fact.h"
%}
%include "fact.h"
Steps to build locally
- Copy the files into a directory and change to that directory. In this case I'll use libgofact
- Generate the SWIG wrapper files. Run the following command in your terminal:
swig -c++ -go -cgo -intgosize 64 fact.i
- Copy the directory to $GOPATH/src
cp -r libgofact $GOPATH/src
cd $GOPATH/src/libgofact
go install -x
- Now you can use libgofact like any other package. Here it is an example:
package main
import (
"fmt"
"libgofact"
)
func main() {
fmt.Println(libfact.Factorial(5))
}
Steps to build on GitHub
- Copy the files into a directory and change to that directory. In this case I'll use libgofact
- Generate the SWIG wrapper files. Run the following command in your terminal:
swig -c++ -go -cgo -intgosize 64 fact.i
- Push your directory to GitHub: github.com/gtoscano/libmyfact
- Install the package
go get github.com/gtoscano/libgithubfact
cd $GOPATH/src/github.com/gtoscano/libgfact
go install -x
- Now you can use libmyfact like any other package. Here it is an example:
package main
import (
"fmt"
"github.com/gtoscano/libmyfact"
)
func main() {
fmt.Println(libfact.Factorial(5))
}
##
#####Example Application Code that uses simplelib.go and simplelib_wrap.cxx
You an also look at the unit tests in `simplelib_test.go`.
```go
package main
import (
"fmt"
"github.com/zacg/simplelib"
)
func main() {
simpleClass := simplelib.NewSimpleClass()
result := simpleClass.Hello()
fmt.Println(result)
strings := simplelib.NewStringVector()
simpleClass.HelloString(strings)
var i int64
for i = 0; i < strings.Size(); i++ {
fmt.Println(strings.Get(int(i)))
}
bytes := simplelib.NewByteVector()
simpleClass.HelloBytes(bytes)
for i = 0; i < bytes.Size(); i++ {
fmt.Printf("%c", bytes.Get(int(i)))
}
fmt.Println("")
}