Last active
March 10, 2016 23:52
-
-
Save daemonl/4d5212f8d2bce02bac5a to your computer and use it in GitHub Desktop.
CGO and FFI - Struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# npm install ffi | |
go build -o libpoint.so -buildmode=c-shared libpoint.go | |
node test.js |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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