Skip to content

Instantly share code, notes, and snippets.

@daemonl
Last active March 10, 2016 23:52
Show Gist options
  • Save daemonl/4d5212f8d2bce02bac5a to your computer and use it in GitHub Desktop.
Save daemonl/4d5212f8d2bce02bac5a to your computer and use it in GitHub Desktop.
CGO and FFI - Struct
package main
/*
struct point {
int x;
int y;
};
*/
import "C"
// BEGIN C Compatibility
func (p C.struct_point) InGo() Point {
return Point{
X: int(p.x),
Y: int(p.y),
}
}
//export add
func add(cpoint C.struct_point) C.int {
point := cpoint.InGo()
return C.int(point.Add())
}
// END C Compatibility
// Point represents a point on a cartesian plane
type Point struct {
X int
Y int
}
// Add just adds X and Y
func (p Point) Add() int {
return p.X + p.Y
}
// Apparently required for the compiler. Needs more reading
func main() {}
#!/bin/bash
# npm install ffi
go build -o libpoint.so -buildmode=c-shared libpoint.go
node test.js
const ffi = require('ffi');
const Struct = require('ref-struct');
var Point = Struct({
'x': 'int',
'y': 'int',
})
const libpoint = ffi.Library('./libpoint', {
'add': ['int', [Point]],
});
var p = new Point();
p.x = 5;
p.y = 20;
console.log(libpoint.add(p));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment