Permalink
Browse files

error with sqrt and free

  • Loading branch information...
1 parent ef3c6b1 commit 09207d633e83bf71affacef6c9984b84fc2d0972 @tebeka tebeka committed Mar 21, 2013
Showing with 27 additions and 28 deletions.
  1. +1 −1 2013/import-c.slide
  2. +17 −0 2013/import-c/err.go
  3. +9 −7 2013/import-c/str3.go
  4. +0 −20 2013/import-c/strtol.go
View
2 2013/import-c.slide
@@ -77,7 +77,7 @@ Note that are other options (such as [[http://www.swig.org/][swig]])
* Go Style Errors
-.play import-c/strtol.go
+.play import-c/err.go
* Case Study - snowball
View
17 2013/import-c/err.go
@@ -0,0 +1,17 @@
+package main
+
+// #include <math.h>
+// #cgo LDFLAGS: -lm
+import "C"
+
+import (
+ "fmt"
+)
+
+func main() {
+ i, err := C.sqrt(-1)
+ if err != nil {
+ fmt.Printf("error: %s\n", err)
+ }
+ fmt.Printf("i = %v\n", i)
+}
View
16 2013/import-c/str3.go
@@ -3,18 +3,20 @@ package main
// #include <string.h>
// #include <stdlib.h>
import "C"
+import "fmt"
+import "unsafe"
-import (
- "fmt"
- "unsafe"
-)
+func free(cstr *C.char) {
+ C.free(unsafe.Pointer(cstr))
+}
func main() {
str := "Gophers Rock!"
+ cstr:= C.CString(str)
+ defer free(cstr)
+
dup := C.strdup(C.CString(str))
- defer func() {
- C.free(unsafe.Pointer(dup))
- }()
+ defer free(dup)
gostr := C.GoString(dup)
fmt.Println(gostr)
View
20 2013/import-c/strtol.go
@@ -1,20 +0,0 @@
-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)
- }
-}

0 comments on commit 09207d6

Please sign in to comment.