SlideShare a Scribd company logo
1 of 40
Download to read offline
Hidden Dragons of
CGO:
Hard-learned
Lessons from Writing
Go Wrappers
October 15, 2019
2
Outline
●
Motivation & Background – YottaDB, C API, Go, CGO
●
Parameter Passing
●
Callbacks
●
Garbage Collection (common thread)
●
Questions & Answers
3
YottaDBⓇ
– https://yottadb.com
●
A mature, high performance, hierarchical key-value
NoSQL database whose code base scales up to
mission-critical applications like large real-time core-
banking and electronic health records, and also
scales down to run on platforms like the Raspberry Pi
Zero, as well as everything in-between.
●
Rock Solid. Lightning Fast. Secure. Pick any three.
YottaDB is a registered trademark of YottaDB LLC
4
Key-Value Tuples
["Capital","Belgium","Brussels"]
["Capital","Thailand","Bangkok"]
["Capital","USA","Washington,DC"]
Key
Value
Always sorted – YottaDB
means never having to say
you’re sorting!
5
Schemaless
["Capital","Belgium","Brussels"]
["Capital","Thailand","Bangkok"]
["Capital","USA","Washington,DC"]
["Population","Belgium",13670000]
["Population","Thailand",84140000]
["Population","USA",325737000]
Schema
determined
entirely by
application –
YottaDB assigns
no meaning
Numbers and strings
(blobs) can be freely
intermixed in values
and keys except first
Default order for each key:
•
Empty string ("")
•
Canonical numbers in numeric order
•
Strings (blobs) in lexical order
6
Mix Key Sizes
["Capital","Belgium","Brussels"]
["Capital","Thailand","Bangkok"]
["Capital","USA","Washington,DC"]
["Population","Belgium",13670000]
["Population","Thailand",84140000]
["Population","USA",325737000]
["Population","USA",17900802,3929326]
["Population","USA",18000804,5308483]
…
["Population","USA",20100401,308745538]
"Population" + 1 more key
means value is latest
population
"Population" + 2 more keys
means value is population on
date represented by last key
yyyymmdd
7
Keys Array References⟷
Population("Belgium")=13670000
Population("Thailand")=84140000
Population("USA")=325737000
Population("USA",17900802)=3929326
Population("USA",18000804)=5308483
…
Population("USA",20100401)=308745538
First key is
variable name
Other keys are
subscripts
Array references are a familiar
programming paradign
Any JSON structure is representable
as a tree, but not vice versa
8
Sharing and Persistence – Database Access
●
Process private, available only for lifetime of process
Population("Belgium")
Population("Thailand
Population("USA")
●
Shared across processes, persistent beyond lifetime
of any process
^Population("Belgium")
^Population("Thailand")
^Population("USA")
Spot the difference?
“global” variables
“local” variables
9
C
●
Low-level programming language developed in 1972
by Dennis Ritchie
●
Lingua Franca of computing
– Everything speaks C; Linux machines, embedded
systems, IOT devices, Android, … everything
●
Static typing, manual memory management
●
Low-level primitives (casting bits, pointer math)
10
C API
11
Golang
●
“Go is an open source programming language that
makes it easy to build simple, reliable, and efficient
software. “
– https://golang.org/
●
Programming language from Google
– Static typing
– Cooperative multithreading
– Mix of C, Erlang, and “Java”
12
Go API
13
How about a Go API to YottaDB?
●
Everything we do is 100% free / open source
●
We make money from support contracts and funded
enhancements
●
What could be simpler than a Go wrapper to the C
API as a funded enhancement?
14
Finoskov [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)]
Yes, indeed, what could
be simpler?
15
CGO
●
https://golang.org/cmd/cgo/
– A lot of code is written in C (GUI libraries, databases,
math libraries, …); calling into that code opens a whole
new world of possibilities
– C is not garbage collected; every C program is
responsible for its own memory allocations (malloc) and
frees; CGO attempts to work around this by creating
rules
16
Passing Go Pointers to C
“Go code may pass a Go pointer to C provided the Go memory
to which it points does not contain any Go pointers. The C code
must preserve this property: it must not store any Go pointers in
Go memory, even temporarily. When passing a pointer to a field
in a struct, the Go memory in question is the memory occupied
by the field, not the entire struct. When passing a pointer to an
element in an array or slice, the Go memory in question is the
entire array or the entire backing array of the slice. “
●
https://golang.org/cmd/cgo/#hdr-Passing_pointers
17
Integers are OK
package main
import "fmt"
// int myFunc(int r1) {
// return r1 + 42;
// }
import "C"
func main() {
fmt.Printf("%v", C.myFunc(22))
}
18
C char is an Integer
package main
import "fmt"
// int myFunc(char c1) {
// return c1 + 42;
// }
import "C"
func main() {
fmt.Printf("%v", C.myFunc(22))
}
19
C Strings are not Go Strings
●
Compilation
error – a Go
string is a
descriptor
unlike a C
string
package main
// #include <stdio.h>
// void myFunc(char *c1) {
// printf("Hello %s!n", c1);
// }
import "C"
func main() {
C.myFunc("world!")
}
20
Passing a Reference to 1st
Element …1
●
Functionally
correct
●
Protected from
garbage
collection
package main
import "unsafe"
// #include <stdio.h>
// void myFunc(void *c1) {
// printf("Hello %s!n", (char*)c1);
// }
import "C"
func main() {
msg := ([]byte)("world!")
C.myFunc(unsafe.Pointer(&msg[0]))
}
21
Passing a Reference to 1st
Element …2
●
Also
functionally
correct
●
Also protected
from garbage
collection
package main
import "unsafe"
// #include <stdio.h>
// void myFunc(char *c1) {
// printf("Hello %s!n", c1);
// }
import "C"
type BufferStruct struct {
buff []byte
}
func main() {
myBuff := BufferStruct{([]byte)("world!")}
C.myFunc((*C.char)(unsafe.Pointer(&myBuff.buff[0])))
}
22
Cannot Pass a Structure with a Pointer …1
●
Compilation
error
package main
// #include <stdio.h>
// typedef struct {
// char *msg;
// } myStruct;
// void myFunc(myStruct *strct) {
// printf("Hello %s!n", strct->msg);
// }
import "C"
func main() {
msg := C.myStruct{"world!"}
C.myFunc(&msg)
}
23
Cannot Pass a Structure with a Pointer …2
●
Compiles
●
Runtime
error
package main
import "unsafe"
// #include <stdio.h>
// typedef struct {
// char *msg;
// } myStruct;
// void myFunc(myStruct *strct) {
// printf("Hello %s!n", strct->msg);
// }
import "C"
func main() {
val := ([]byte)("world!")
msg := C.myStruct{(*C.char)(unsafe.Pointer(&val[0]))}
C.myFunc(&msg)
}
24
Go Structures with Pointers to C structs …1
●
Compiles
●
Runs
●
But leaks
memory
package main
// #include <stdio.h>
// typedef struct {
// char *msg;
// } myStruct;
// void myFunc(myStruct *strct) {
// printf("Hello %s!n", strct->msg);
// }
import "C"
func main() {
msg := C.myStruct{C.CString("world")}
C.myFunc(&msg)
}
25
Go Structures with Pointers to C structs …2
●
Compiles
●
Runs
●
Can use
explicit free
– Unfriendly
– Error prone
package main
// #include <stdio.h>
// #include <stdlib.h>
// typedef struct {
// char *msg;
// } myStruct;
// void myFunc(myStruct *strct) {
// printf("Hello %s!n", strct->msg);
// }
import "C"
func main() {
msg := C.myStruct{C.CString("world")}
defer C.free(msg.msg)
C.myFunc(&msg)
}
26
●
Finalizers
– Annoys
Gophers
●
Can still cause
segmentation
violations!
package main
import "unsafe"
// #include <stdio.h>
// #include <stdlib.h>
// typedef struct {
// char *msg;
// } myStruct;
// void myFunc(myStruct *strct) {
// printf("Hello %s!n", strct->msg);
// }
import "C"
func main() {
msg := C.myStruct{C.CString("world")}
runtime.SetFinalizer(&msg, func(t *C.myStruct) {
C.free(unsafe.Pointer(t.msg))
})
C.myFunc(&msg)
}
Go Structures with Pointers to C structs …3
27
●
Finalizers
●
KeepAlive to
protect from
garbage
collection
package main
import "unsafe"
// #include <stdio.h>
// #include <stdlib.h>
// typedef struct {
// char *msg;
// } myStruct;
// void myFunc(myStruct *strct) {
// printf("Hello %s!n", strct->msg);
// }
import "C"
func main() {
msg := C.myStruct{C.CString("world")}
runtime.SetFinalizer(&msg, func(t *C.myStruct) {
C.free(unsafe.Pointer(t.msg))
})
C.myFunc(&msg)
runtime.KeepAlive(&msg)
}
Go Structures with Pointers to C structs
28
Callbacks
●
Common in C, especially with UI work
●
YottaDB uses callbacks for ACID transactions
29
Callbacks – “Obvious approach”
●
Does not
compile
package main
// void do_callback(void (*cb)()) {
// cb();
// }
import "C"
func callback() {
fmt.Printf("Here!n")
}
func main() {
C.do_callback(callback)
}
30
Callbacks – “Obvious” Solution
●
Split into
two files
●
C func to
return
callback
package main
// void do_callback(void (*cb)())
{
// cb();
// }
// extern void callback();
// void (*get_callback())() {
// return callback;
// }
import "C"
func main() {
C.do_callback(C.get_callback())
}
package main
import "fmt"
//export callback
import "C"
func callback() {
fmt.Printf("Here!n")
}
31
●
Error prone
●
Makes testing hard
– Can’t import C in test code
●
Feels kludgy
Callbacks – “Obvious” Drawbacks
32
Callbacks – Alternative Approach
●
Write a callback function to pass back an index to a
hashmap that stores the Golang callback; use
closure for passing parameters
●
Less error prone, with small performance hit
●
Still feels kludgy – but not so much to gophers
33
Callback for Transaction Processing
Base
Application
yottadb.
TpST()
Transaction
Logic
Call
Call
Return
Return
34
Closure
func helloWorld(i int) {
(func() {
fmt.Printf("i: %v", i)
})()
}
35
Callbacks – Alternative Code Fragment
var tpIndex uint64
var tpMap sync.Map
// YdbTpStWrapper is private callback to wrap calls to a Go closure for TpST
//export ydbTpStWrapper
func ydbTpStWrapper(tptoken uint64, errstr *C.ydb_buffer_t, tpfnparm
unsafe.Pointer) int32 {
var errbuff BufferT
index := *((*uint64)(tpfnparm))
v, ok := tpMap.Load(index)
if !ok {
panic("YDB: Could not find callback routine")
}
errbuff.BufferTFromPtr((unsafe.Pointer)(errstr))
return (v.(func(uint64, *BufferT) int32))(tptoken, &errbuff)
}
36
Taming the CGO Dragons
●
Issues may not show up until garbage collection is
occurs
– Sometimes only after days of intensive use
– And even then only at random
37
Poking the CGO Dragons
●
Trigger more garbage collection
– export GOGC=1
●
Catch for Go pointers being passed
– export GODEBUG=”cgocheck=2”
●
Horrible. Mean. Ugly. Tests.
38
CGO Dragons are Slumbering, not Slain
●
Go still believes it owns the process
– Go developers know best because they develop Go
primarily for their own use
●
Another dragon not discussed here – signal handlers
●
The cost of sharing a cave with a dragon is eternal
vigilance
– Test continuously, and then test some more
39
Thank You!

More Related Content

What's hot

Let’s template
Let’s templateLet’s template
Let’s templateAllenKao7
 
Unit Testing your React / Redux app (@BucharestJS)
Unit Testing your React / Redux app (@BucharestJS)Unit Testing your React / Redux app (@BucharestJS)
Unit Testing your React / Redux app (@BucharestJS)Alin Pandichi
 
Golang from Scala developer’s perspective
Golang from Scala developer’s perspectiveGolang from Scala developer’s perspective
Golang from Scala developer’s perspectiveSveta Bozhko
 
Indy meetup#7 effective unit-testing-mule
Indy meetup#7 effective unit-testing-muleIndy meetup#7 effective unit-testing-mule
Indy meetup#7 effective unit-testing-muleikram_ahamed
 
Meetup React Sanca - 29/11/18 - React Testing
Meetup React Sanca - 29/11/18 - React TestingMeetup React Sanca - 29/11/18 - React Testing
Meetup React Sanca - 29/11/18 - React TestingAugusto Lazaro
 
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...OdessaJS Conf
 
Python debuggers slides
Python debuggers slidesPython debuggers slides
Python debuggers slidesmattboehm
 
Trunk-Based Development and Toggling
Trunk-Based Development and TogglingTrunk-Based Development and Toggling
Trunk-Based Development and TogglingBryan Liu
 
API Design in the Modern Era - Architecture Next 2020
API Design in the Modern Era - Architecture Next 2020API Design in the Modern Era - Architecture Next 2020
API Design in the Modern Era - Architecture Next 2020Eran Stiller
 
OpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideOpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideTim Burks
 
The new way to extend VSTS Build and Release
The new way to extend VSTS Build and ReleaseThe new way to extend VSTS Build and Release
The new way to extend VSTS Build and ReleaseJesse Houwing
 
"Technical Challenges behind Visual IDE for React Components" Tetiana Mandziuk
"Technical Challenges behind Visual IDE for React Components" Tetiana Mandziuk"Technical Challenges behind Visual IDE for React Components" Tetiana Mandziuk
"Technical Challenges behind Visual IDE for React Components" Tetiana MandziukFwdays
 
API Automation Testing Using RestAssured+Cucumber
API Automation Testing Using RestAssured+CucumberAPI Automation Testing Using RestAssured+Cucumber
API Automation Testing Using RestAssured+CucumberKnoldus Inc.
 
Self-service PR-based Terraform
Self-service PR-based TerraformSelf-service PR-based Terraform
Self-service PR-based TerraformAndrew Kirkpatrick
 
ATDD Using Robot Framework
ATDD Using Robot FrameworkATDD Using Robot Framework
ATDD Using Robot FrameworkPekka Klärck
 
OpenDaylight Developers Experience 1.5: Eclipse Setup, HOT reload, future plans
OpenDaylight Developers Experience 1.5: Eclipse Setup, HOT reload, future plansOpenDaylight Developers Experience 1.5: Eclipse Setup, HOT reload, future plans
OpenDaylight Developers Experience 1.5: Eclipse Setup, HOT reload, future plansMichael Vorburger
 
Writing REST APIs with OpenAPI and Swagger Ada
Writing REST APIs with OpenAPI and Swagger AdaWriting REST APIs with OpenAPI and Swagger Ada
Writing REST APIs with OpenAPI and Swagger AdaStephane Carrez
 
TDD for APIs @ Europython 2015, Bilbao by Michael Kuehne
TDD for APIs @ Europython 2015, Bilbao by Michael KuehneTDD for APIs @ Europython 2015, Bilbao by Michael Kuehne
TDD for APIs @ Europython 2015, Bilbao by Michael KuehneMichael Kuehne-Schlinkert
 

What's hot (20)

Let’s template
Let’s templateLet’s template
Let’s template
 
Unit Testing your React / Redux app (@BucharestJS)
Unit Testing your React / Redux app (@BucharestJS)Unit Testing your React / Redux app (@BucharestJS)
Unit Testing your React / Redux app (@BucharestJS)
 
Golang from Scala developer’s perspective
Golang from Scala developer’s perspectiveGolang from Scala developer’s perspective
Golang from Scala developer’s perspective
 
Indy meetup#7 effective unit-testing-mule
Indy meetup#7 effective unit-testing-muleIndy meetup#7 effective unit-testing-mule
Indy meetup#7 effective unit-testing-mule
 
Meetup React Sanca - 29/11/18 - React Testing
Meetup React Sanca - 29/11/18 - React TestingMeetup React Sanca - 29/11/18 - React Testing
Meetup React Sanca - 29/11/18 - React Testing
 
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...
 
Python debuggers slides
Python debuggers slidesPython debuggers slides
Python debuggers slides
 
Trunk-Based Development and Toggling
Trunk-Based Development and TogglingTrunk-Based Development and Toggling
Trunk-Based Development and Toggling
 
API Design in the Modern Era - Architecture Next 2020
API Design in the Modern Era - Architecture Next 2020API Design in the Modern Era - Architecture Next 2020
API Design in the Modern Era - Architecture Next 2020
 
OpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideOpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-Side
 
The new way to extend VSTS Build and Release
The new way to extend VSTS Build and ReleaseThe new way to extend VSTS Build and Release
The new way to extend VSTS Build and Release
 
"Technical Challenges behind Visual IDE for React Components" Tetiana Mandziuk
"Technical Challenges behind Visual IDE for React Components" Tetiana Mandziuk"Technical Challenges behind Visual IDE for React Components" Tetiana Mandziuk
"Technical Challenges behind Visual IDE for React Components" Tetiana Mandziuk
 
API Automation Testing Using RestAssured+Cucumber
API Automation Testing Using RestAssured+CucumberAPI Automation Testing Using RestAssured+Cucumber
API Automation Testing Using RestAssured+Cucumber
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Test driving QML
Test driving QMLTest driving QML
Test driving QML
 
Self-service PR-based Terraform
Self-service PR-based TerraformSelf-service PR-based Terraform
Self-service PR-based Terraform
 
ATDD Using Robot Framework
ATDD Using Robot FrameworkATDD Using Robot Framework
ATDD Using Robot Framework
 
OpenDaylight Developers Experience 1.5: Eclipse Setup, HOT reload, future plans
OpenDaylight Developers Experience 1.5: Eclipse Setup, HOT reload, future plansOpenDaylight Developers Experience 1.5: Eclipse Setup, HOT reload, future plans
OpenDaylight Developers Experience 1.5: Eclipse Setup, HOT reload, future plans
 
Writing REST APIs with OpenAPI and Swagger Ada
Writing REST APIs with OpenAPI and Swagger AdaWriting REST APIs with OpenAPI and Swagger Ada
Writing REST APIs with OpenAPI and Swagger Ada
 
TDD for APIs @ Europython 2015, Bilbao by Michael Kuehne
TDD for APIs @ Europython 2015, Bilbao by Michael KuehneTDD for APIs @ Europython 2015, Bilbao by Michael Kuehne
TDD for APIs @ Europython 2015, Bilbao by Michael Kuehne
 

Similar to Hidden Dragons of CGO

Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016maiktoepfer
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about goDvir Volk
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io
 
GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005Saleem Ansari
 
ICT1002-W8-LEC-Introduction-to-C.pdf
ICT1002-W8-LEC-Introduction-to-C.pdfICT1002-W8-LEC-Introduction-to-C.pdf
ICT1002-W8-LEC-Introduction-to-C.pdfssuser33f16f
 
Untitled presentation(4)
Untitled presentation(4)Untitled presentation(4)
Untitled presentation(4)chan20kaur
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeMicrosoft Tech Community
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeMicrosoft Tech Community
 
Introduction-to-C-Part-1 (1).doc
Introduction-to-C-Part-1 (1).docIntroduction-to-C-Part-1 (1).doc
Introduction-to-C-Part-1 (1).docMayurWagh46
 
Objective c beginner's guide
Objective c beginner's guideObjective c beginner's guide
Objective c beginner's guideTiago Faller
 
Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfAnassElHousni
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language CourseVivek chan
 

Similar to Hidden Dragons of CGO (20)

Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 
How to build the Web
How to build the WebHow to build the Web
How to build the Web
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and Golang
 
GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005
 
ICT1002-W8-LEC-Introduction-to-C.pdf
ICT1002-W8-LEC-Introduction-to-C.pdfICT1002-W8-LEC-Introduction-to-C.pdf
ICT1002-W8-LEC-Introduction-to-C.pdf
 
Untitled presentation(4)
Untitled presentation(4)Untitled presentation(4)
Untitled presentation(4)
 
Qt coin3d soqt
Qt coin3d soqtQt coin3d soqt
Qt coin3d soqt
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
Lab 1.pptx
Lab 1.pptxLab 1.pptx
Lab 1.pptx
 
C++Basics2022.pptx
C++Basics2022.pptxC++Basics2022.pptx
C++Basics2022.pptx
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
 
Introduction-to-C-Part-1 (1).doc
Introduction-to-C-Part-1 (1).docIntroduction-to-C-Part-1 (1).doc
Introduction-to-C-Part-1 (1).doc
 
Objective c beginner's guide
Objective c beginner's guideObjective c beginner's guide
Objective c beginner's guide
 
Programming in c
Programming in cProgramming in c
Programming in c
 
1 c introduction
1 c introduction1 c introduction
1 c introduction
 
C tutorial
C tutorialC tutorial
C tutorial
 
Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdf
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language Course
 

More from All Things Open

Building Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityBuilding Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityAll Things Open
 
Modern Database Best Practices
Modern Database Best PracticesModern Database Best Practices
Modern Database Best PracticesAll Things Open
 
Open Source and Public Policy
Open Source and Public PolicyOpen Source and Public Policy
Open Source and Public PolicyAll Things Open
 
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...All Things Open
 
The State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashThe State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashAll Things Open
 
Total ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptTotal ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptAll Things Open
 
What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?All Things Open
 
How to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractHow to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractAll Things Open
 
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlowAll Things Open
 
DEI Challenges and Success
DEI Challenges and SuccessDEI Challenges and Success
DEI Challenges and SuccessAll Things Open
 
Scaling Web Applications with Background
Scaling Web Applications with BackgroundScaling Web Applications with Background
Scaling Web Applications with BackgroundAll Things Open
 
Supercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblySupercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblyAll Things Open
 
Using SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksUsing SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksAll Things Open
 
Configuration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptConfiguration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptAll Things Open
 
Scaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramScaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramAll Things Open
 
Build Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceBuild Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceAll Things Open
 
Deploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamDeploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamAll Things Open
 
Sudo – Giving access while staying in control
Sudo – Giving access while staying in controlSudo – Giving access while staying in control
Sudo – Giving access while staying in controlAll Things Open
 
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsFortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsAll Things Open
 
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...All Things Open
 

More from All Things Open (20)

Building Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityBuilding Reliability - The Realities of Observability
Building Reliability - The Realities of Observability
 
Modern Database Best Practices
Modern Database Best PracticesModern Database Best Practices
Modern Database Best Practices
 
Open Source and Public Policy
Open Source and Public PolicyOpen Source and Public Policy
Open Source and Public Policy
 
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
 
The State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashThe State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil Nash
 
Total ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptTotal ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScript
 
What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?
 
How to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractHow to Write & Deploy a Smart Contract
How to Write & Deploy a Smart Contract
 
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 
DEI Challenges and Success
DEI Challenges and SuccessDEI Challenges and Success
DEI Challenges and Success
 
Scaling Web Applications with Background
Scaling Web Applications with BackgroundScaling Web Applications with Background
Scaling Web Applications with Background
 
Supercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblySupercharging tutorials with WebAssembly
Supercharging tutorials with WebAssembly
 
Using SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksUsing SQL to Find Needles in Haystacks
Using SQL to Find Needles in Haystacks
 
Configuration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptConfiguration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit Intercept
 
Scaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramScaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship Program
 
Build Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceBuild Developer Experience Teams for Open Source
Build Developer Experience Teams for Open Source
 
Deploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamDeploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache Beam
 
Sudo – Giving access while staying in control
Sudo – Giving access while staying in controlSudo – Giving access while staying in control
Sudo – Giving access while staying in control
 
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsFortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
 
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

Hidden Dragons of CGO

  • 1. Hidden Dragons of CGO: Hard-learned Lessons from Writing Go Wrappers October 15, 2019
  • 2. 2 Outline ● Motivation & Background – YottaDB, C API, Go, CGO ● Parameter Passing ● Callbacks ● Garbage Collection (common thread) ● Questions & Answers
  • 3. 3 YottaDBⓇ – https://yottadb.com ● A mature, high performance, hierarchical key-value NoSQL database whose code base scales up to mission-critical applications like large real-time core- banking and electronic health records, and also scales down to run on platforms like the Raspberry Pi Zero, as well as everything in-between. ● Rock Solid. Lightning Fast. Secure. Pick any three. YottaDB is a registered trademark of YottaDB LLC
  • 5. 5 Schemaless ["Capital","Belgium","Brussels"] ["Capital","Thailand","Bangkok"] ["Capital","USA","Washington,DC"] ["Population","Belgium",13670000] ["Population","Thailand",84140000] ["Population","USA",325737000] Schema determined entirely by application – YottaDB assigns no meaning Numbers and strings (blobs) can be freely intermixed in values and keys except first Default order for each key: • Empty string ("") • Canonical numbers in numeric order • Strings (blobs) in lexical order
  • 7. 7 Keys Array References⟷ Population("Belgium")=13670000 Population("Thailand")=84140000 Population("USA")=325737000 Population("USA",17900802)=3929326 Population("USA",18000804)=5308483 … Population("USA",20100401)=308745538 First key is variable name Other keys are subscripts Array references are a familiar programming paradign Any JSON structure is representable as a tree, but not vice versa
  • 8. 8 Sharing and Persistence – Database Access ● Process private, available only for lifetime of process Population("Belgium") Population("Thailand Population("USA") ● Shared across processes, persistent beyond lifetime of any process ^Population("Belgium") ^Population("Thailand") ^Population("USA") Spot the difference? “global” variables “local” variables
  • 9. 9 C ● Low-level programming language developed in 1972 by Dennis Ritchie ● Lingua Franca of computing – Everything speaks C; Linux machines, embedded systems, IOT devices, Android, … everything ● Static typing, manual memory management ● Low-level primitives (casting bits, pointer math)
  • 11. 11 Golang ● “Go is an open source programming language that makes it easy to build simple, reliable, and efficient software. “ – https://golang.org/ ● Programming language from Google – Static typing – Cooperative multithreading – Mix of C, Erlang, and “Java”
  • 13. 13 How about a Go API to YottaDB? ● Everything we do is 100% free / open source ● We make money from support contracts and funded enhancements ● What could be simpler than a Go wrapper to the C API as a funded enhancement?
  • 14. 14 Finoskov [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)] Yes, indeed, what could be simpler?
  • 15. 15 CGO ● https://golang.org/cmd/cgo/ – A lot of code is written in C (GUI libraries, databases, math libraries, …); calling into that code opens a whole new world of possibilities – C is not garbage collected; every C program is responsible for its own memory allocations (malloc) and frees; CGO attempts to work around this by creating rules
  • 16. 16 Passing Go Pointers to C “Go code may pass a Go pointer to C provided the Go memory to which it points does not contain any Go pointers. The C code must preserve this property: it must not store any Go pointers in Go memory, even temporarily. When passing a pointer to a field in a struct, the Go memory in question is the memory occupied by the field, not the entire struct. When passing a pointer to an element in an array or slice, the Go memory in question is the entire array or the entire backing array of the slice. “ ● https://golang.org/cmd/cgo/#hdr-Passing_pointers
  • 17. 17 Integers are OK package main import "fmt" // int myFunc(int r1) { // return r1 + 42; // } import "C" func main() { fmt.Printf("%v", C.myFunc(22)) }
  • 18. 18 C char is an Integer package main import "fmt" // int myFunc(char c1) { // return c1 + 42; // } import "C" func main() { fmt.Printf("%v", C.myFunc(22)) }
  • 19. 19 C Strings are not Go Strings ● Compilation error – a Go string is a descriptor unlike a C string package main // #include <stdio.h> // void myFunc(char *c1) { // printf("Hello %s!n", c1); // } import "C" func main() { C.myFunc("world!") }
  • 20. 20 Passing a Reference to 1st Element …1 ● Functionally correct ● Protected from garbage collection package main import "unsafe" // #include <stdio.h> // void myFunc(void *c1) { // printf("Hello %s!n", (char*)c1); // } import "C" func main() { msg := ([]byte)("world!") C.myFunc(unsafe.Pointer(&msg[0])) }
  • 21. 21 Passing a Reference to 1st Element …2 ● Also functionally correct ● Also protected from garbage collection package main import "unsafe" // #include <stdio.h> // void myFunc(char *c1) { // printf("Hello %s!n", c1); // } import "C" type BufferStruct struct { buff []byte } func main() { myBuff := BufferStruct{([]byte)("world!")} C.myFunc((*C.char)(unsafe.Pointer(&myBuff.buff[0]))) }
  • 22. 22 Cannot Pass a Structure with a Pointer …1 ● Compilation error package main // #include <stdio.h> // typedef struct { // char *msg; // } myStruct; // void myFunc(myStruct *strct) { // printf("Hello %s!n", strct->msg); // } import "C" func main() { msg := C.myStruct{"world!"} C.myFunc(&msg) }
  • 23. 23 Cannot Pass a Structure with a Pointer …2 ● Compiles ● Runtime error package main import "unsafe" // #include <stdio.h> // typedef struct { // char *msg; // } myStruct; // void myFunc(myStruct *strct) { // printf("Hello %s!n", strct->msg); // } import "C" func main() { val := ([]byte)("world!") msg := C.myStruct{(*C.char)(unsafe.Pointer(&val[0]))} C.myFunc(&msg) }
  • 24. 24 Go Structures with Pointers to C structs …1 ● Compiles ● Runs ● But leaks memory package main // #include <stdio.h> // typedef struct { // char *msg; // } myStruct; // void myFunc(myStruct *strct) { // printf("Hello %s!n", strct->msg); // } import "C" func main() { msg := C.myStruct{C.CString("world")} C.myFunc(&msg) }
  • 25. 25 Go Structures with Pointers to C structs …2 ● Compiles ● Runs ● Can use explicit free – Unfriendly – Error prone package main // #include <stdio.h> // #include <stdlib.h> // typedef struct { // char *msg; // } myStruct; // void myFunc(myStruct *strct) { // printf("Hello %s!n", strct->msg); // } import "C" func main() { msg := C.myStruct{C.CString("world")} defer C.free(msg.msg) C.myFunc(&msg) }
  • 26. 26 ● Finalizers – Annoys Gophers ● Can still cause segmentation violations! package main import "unsafe" // #include <stdio.h> // #include <stdlib.h> // typedef struct { // char *msg; // } myStruct; // void myFunc(myStruct *strct) { // printf("Hello %s!n", strct->msg); // } import "C" func main() { msg := C.myStruct{C.CString("world")} runtime.SetFinalizer(&msg, func(t *C.myStruct) { C.free(unsafe.Pointer(t.msg)) }) C.myFunc(&msg) } Go Structures with Pointers to C structs …3
  • 27. 27 ● Finalizers ● KeepAlive to protect from garbage collection package main import "unsafe" // #include <stdio.h> // #include <stdlib.h> // typedef struct { // char *msg; // } myStruct; // void myFunc(myStruct *strct) { // printf("Hello %s!n", strct->msg); // } import "C" func main() { msg := C.myStruct{C.CString("world")} runtime.SetFinalizer(&msg, func(t *C.myStruct) { C.free(unsafe.Pointer(t.msg)) }) C.myFunc(&msg) runtime.KeepAlive(&msg) } Go Structures with Pointers to C structs
  • 28. 28 Callbacks ● Common in C, especially with UI work ● YottaDB uses callbacks for ACID transactions
  • 29. 29 Callbacks – “Obvious approach” ● Does not compile package main // void do_callback(void (*cb)()) { // cb(); // } import "C" func callback() { fmt.Printf("Here!n") } func main() { C.do_callback(callback) }
  • 30. 30 Callbacks – “Obvious” Solution ● Split into two files ● C func to return callback package main // void do_callback(void (*cb)()) { // cb(); // } // extern void callback(); // void (*get_callback())() { // return callback; // } import "C" func main() { C.do_callback(C.get_callback()) } package main import "fmt" //export callback import "C" func callback() { fmt.Printf("Here!n") }
  • 31. 31 ● Error prone ● Makes testing hard – Can’t import C in test code ● Feels kludgy Callbacks – “Obvious” Drawbacks
  • 32. 32 Callbacks – Alternative Approach ● Write a callback function to pass back an index to a hashmap that stores the Golang callback; use closure for passing parameters ● Less error prone, with small performance hit ● Still feels kludgy – but not so much to gophers
  • 33. 33 Callback for Transaction Processing Base Application yottadb. TpST() Transaction Logic Call Call Return Return
  • 34. 34 Closure func helloWorld(i int) { (func() { fmt.Printf("i: %v", i) })() }
  • 35. 35 Callbacks – Alternative Code Fragment var tpIndex uint64 var tpMap sync.Map // YdbTpStWrapper is private callback to wrap calls to a Go closure for TpST //export ydbTpStWrapper func ydbTpStWrapper(tptoken uint64, errstr *C.ydb_buffer_t, tpfnparm unsafe.Pointer) int32 { var errbuff BufferT index := *((*uint64)(tpfnparm)) v, ok := tpMap.Load(index) if !ok { panic("YDB: Could not find callback routine") } errbuff.BufferTFromPtr((unsafe.Pointer)(errstr)) return (v.(func(uint64, *BufferT) int32))(tptoken, &errbuff) }
  • 36. 36 Taming the CGO Dragons ● Issues may not show up until garbage collection is occurs – Sometimes only after days of intensive use – And even then only at random
  • 37. 37 Poking the CGO Dragons ● Trigger more garbage collection – export GOGC=1 ● Catch for Go pointers being passed – export GODEBUG=”cgocheck=2” ● Horrible. Mean. Ugly. Tests.
  • 38. 38 CGO Dragons are Slumbering, not Slain ● Go still believes it owns the process – Go developers know best because they develop Go primarily for their own use ● Another dragon not discussed here – signal handlers ● The cost of sharing a cave with a dragon is eternal vigilance – Test continuously, and then test some more
  • 39. 39