Permalink
Browse files

struct and errors

  • Loading branch information...
1 parent f2e50fb commit ef3c6b10e1317591e8ba979b1c0f96eeaed2e038 @tebeka tebeka committed Mar 21, 2013
Showing with 35 additions and 9 deletions.
  1. +8 −2 2013/import-c.slide
  2. +20 −0 2013/import-c/strtol.go
  3. +7 −7 2013/import-c/struct.go
View
@@ -20,14 +20,16 @@ We'd like to re-use it and not re-write it.
Provides an easy bridge between Go and C
-Problems
+The Downside
- Hard to find docs (see reference slide)
- Pay attention to memory leaks
- Compilation time grows
+- For C++ you need `extern`"C"` and C like wrapper
Note that are other options (such as [[http://www.swig.org/][swig]])
+
* Minimal Example
.play import-c/sqrt.go
@@ -73,6 +75,10 @@ Note that are other options (such as [[http://www.swig.org/][swig]])
.code import-c/callback/callback.go
+* Go Style Errors
+
+.play import-c/strtol.go
+
* Case Study - snowball
- [[https://bitbucket.org/tebeka/snowball]]
@@ -99,7 +105,7 @@ snowball uses `sb_symbol*` for string
* snowball - List
-The list of languages is a static char* array with a `NULL` sentinal
+The list of languages is a `static`char*` array with a `NULL` sentinal
.code import-c/snowball.go /START_LIST/,/END_LIST/
@@ -0,0 +1,20 @@
+package main
+
+// #include <stdlib.h>
+import "C"
+
+import (
+ "fmt"
+)
+
+func main() {
+ // Notice you can pass nil as NULL
+ i := C.strtol(C.CString("10"), nil, 10)
+ fmt.Println(i)
+
+ // strtol will set errno on errors (in this case, base too large)
+ i, err := C.strtol(C.CString("10"), nil, 100)
+ if err != nil {
+ fmt.Printf("error: %s\n", err)
+ }
+}
@@ -3,21 +3,21 @@ package main
// meanwhile at stdlib.h:
// typedef struct
// {
-// int quot; /* Quotient. */
-// int rem; /* Remainder. */
+// int quot; /* Quotient. */
+// int rem; /* Remainder. */
// } div_t;
// #include <stdlib.h>
import "C"
-
-import (
- "fmt"
-)
+import "fmt"
func main() {
- var dt C.div_t
+ var dt C.div_t // Look Ma! C types
dt = C.div(16, 6)
fmt.Printf("quot: %d, rem: %d\n", dt.quot, dt.rem)
+
+ dt.quot = 17 // Mutate the struct
+ fmt.Printf("%v\n", dt) // %v works as well
}

0 comments on commit ef3c6b1

Please sign in to comment.