Skip to content

Commit 56658d6

Browse files
committed
Add files to generate Go bindings using the c-for-go tool
Signed-off-by: Kevin Klues <[email protected]>
1 parent b5c707c commit 56658d6

File tree

5 files changed

+7750
-0
lines changed

5 files changed

+7750
-0
lines changed

Makefile

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
GEN_DIR = $(PWD)/gen
2+
PKG_DIR = $(PWD)/pkg
3+
GEN_BINDINGS_DIR = $(GEN_DIR)/nvml
4+
PKG_BINDINGS_DIR = $(PKG_DIR)/nvml
5+
6+
SOURCES = $(shell find $(GEN_BINDINGS_DIR) -type f)
7+
8+
.PHONY: all test clean
9+
.PHONY: bindings test-bindings clean-bindings
10+
11+
all: bindings
12+
test: test-bindings
13+
clean: clean-bindings
14+
15+
$(PKG_BINDINGS_DIR): $(SOURCES)
16+
c-for-go -out $(PKG_DIR) $(GEN_BINDINGS_DIR)/nvml.yml
17+
cp $(GEN_BINDINGS_DIR)/*.go $(PKG_BINDINGS_DIR)
18+
cp $(GEN_BINDINGS_DIR)/nvml.h $(PKG_BINDINGS_DIR)
19+
patch $(PKG_BINDINGS_DIR)/nvml.h $(GEN_BINDINGS_DIR)/nvml.h.patch
20+
cd $(PKG_BINDINGS_DIR); \
21+
go tool cgo -godefs types.go > types_gen.go; \
22+
go fmt types_gen.go; \
23+
cd -> /dev/null
24+
rm -rf $(PKG_BINDINGS_DIR)/types.go $(PKG_BINDINGS_DIR)/_obj
25+
26+
bindings: $(PKG_BINDINGS_DIR)
27+
28+
test-bindings: $(PKG_BINDINGS_DIR)
29+
cd $(PKG_BINDINGS_DIR); \
30+
go test -v .; \
31+
cd -> /dev/null
32+
33+
clean-bindings:
34+
rm -rf $(PKG_BINDINGS_DIR)

gen/nvml/cgo_helpers.go

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
2+
3+
package nvml
4+
5+
import (
6+
"unsafe"
7+
)
8+
9+
import "C"
10+
11+
var cgoAllocsUnknown = new(struct{})
12+
13+
type stringHeader struct {
14+
Data unsafe.Pointer
15+
Len int
16+
}
17+
18+
// packPCharString creates a Go string backed by *C.char and avoids copying.
19+
func packPCharString(p *C.char) (raw string) {
20+
if p != nil && *p != 0 {
21+
h := (*stringHeader)(unsafe.Pointer(&raw))
22+
h.Data = unsafe.Pointer(p)
23+
for *p != 0 {
24+
p = (*C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + 1)) // p++
25+
}
26+
h.Len = int(uintptr(unsafe.Pointer(p)) - uintptr(h.Data))
27+
}
28+
return
29+
}
30+
31+
// unpackPCharString represents the data from Go string as *C.char and avoids copying.
32+
func unpackPCharString(str string) (*C.char, *struct{}) {
33+
h := (*stringHeader)(unsafe.Pointer(&str))
34+
return (*C.char)(h.Data), cgoAllocsUnknown
35+
}

0 commit comments

Comments
 (0)