Skip to content

Commit d45f7ee

Browse files
committed
Use *byte instead of unsafe.Pointer for C bridge methods.
1 parent 9c8daf3 commit d45f7ee

File tree

4 files changed

+42
-6
lines changed

4 files changed

+42
-6
lines changed

internal/native/cgo_read.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,12 @@ import "C"
1515
import (
1616
"io"
1717
"log"
18-
"unsafe"
1918
)
2019

2120
//export cgo_read_buffer
2221
func cgo_read_buffer(
2322
bufferIndex C.int,
24-
bufPtr unsafe.Pointer,
23+
bufPtr *byte,
2524
length C.int,
2625
) C.int {
2726
goLength := int(length)

internal/native/cgo_write.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,11 @@ package native
1111
#include "bsdiff.h"
1212
*/
1313
import "C"
14-
import "unsafe"
1514

1615
//export cgo_write_buffer
1716
func cgo_write_buffer(
1817
bufferIndex C.int,
19-
dataPtr unsafe.Pointer,
18+
dataPtr *byte,
2019
size C.int,
2120
) C.int {
2221
buffer := writers.Get(int(bufferIndex))

internal/native/native.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,12 @@ func bytesToUint8PtrAndSize(bytes []byte) (ptr *C.uint8_t, size C.int64_t) {
2828
return
2929
}
3030

31-
func cPtrToSlice(ptr unsafe.Pointer, size int) []byte {
31+
func cPtrToSlice(ptr *byte, size int) []byte {
3232
var slice []byte
3333
sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&slice))
3434
sliceHeader.Cap = size
3535
sliceHeader.Len = size
36-
sliceHeader.Data = uintptr(ptr)
36+
sliceHeader.Data = uintptr(unsafe.Pointer(ptr))
3737

3838
return slice
3939
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Copyright (c) 2017-2025 Carl Kittelberger.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE.txt file.
4+
5+
//go:build cgo && go1.20
6+
// +build cgo,go1.20
7+
8+
package native
9+
10+
import (
11+
"crypto/rand"
12+
"testing"
13+
"unsafe"
14+
15+
"github.com/stretchr/testify/assert"
16+
)
17+
18+
const testBytesLen = 512 * 1024
19+
20+
func makeTestBytes() []byte {
21+
b := make([]byte, testBytesLen)
22+
_, _ = rand.Read(b)
23+
return b
24+
}
25+
26+
func Test_bytesToUint8PtrAndSize(t *testing.T) {
27+
b := makeTestBytes()
28+
ptr, size := bytesToUint8PtrAndSize(b)
29+
assert.EqualValues(t, &b[0], ptr)
30+
assert.EqualValues(t, testBytesLen, size)
31+
}
32+
33+
func Test_cPtrToSlice(t *testing.T) {
34+
b := makeTestBytes()
35+
bytePtr := unsafe.SliceData(b)
36+
b2 := cPtrToSlice(bytePtr, testBytesLen)
37+
assert.Equal(t, b, b2)
38+
}

0 commit comments

Comments
 (0)