Add Extract() method to take out C pointer from BytesConverter without releasing it (#15614)

Signed-off-by: yah01 <yah2er0ne@outlook.com>
This commit is contained in:
yah01 2022-02-27 09:47:53 +08:00 committed by GitHub
parent 6a48071a5c
commit 867cf620ee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 4 deletions

View File

@ -56,6 +56,12 @@ func (converter *BytesConverter) UnsafeGoBytes(cbytes *unsafe.Pointer, len int)
} }
func (converter *BytesConverter) Release(lease int32) { func (converter *BytesConverter) Release(lease int32) {
p := converter.Extract(lease)
C.free(p)
}
func (converter *BytesConverter) Extract(lease int32) unsafe.Pointer {
pI, ok := converter.pointers.LoadAndDelete(lease) pI, ok := converter.pointers.LoadAndDelete(lease)
if !ok { if !ok {
panic("try to release the resource that doesn't exist") panic("try to release the resource that doesn't exist")
@ -66,7 +72,7 @@ func (converter *BytesConverter) Release(lease int32) {
panic("incorrect value type") panic("incorrect value type")
} }
C.free(p) return p
} }
// Make sure only the caller own the converter // Make sure only the caller own the converter
@ -90,4 +96,8 @@ func Release(lease int32) {
globalConverter.Release(lease) globalConverter.Release(lease)
} }
func Extract(lease int32) unsafe.Pointer {
return globalConverter.Extract(lease)
}
// DO NOT provide ReleaseAll() method for global converter // DO NOT provide ReleaseAll() method for global converter

View File

@ -16,7 +16,6 @@ func TestBytesConverter(t *testing.T) {
defer Release(lease) defer Release(lease)
equalBytes(t, data, goBytes) equalBytes(t, data, goBytes)
// data = make([]byte, maxByteArrayLen)
v := byte(0x57) v := byte(0x57)
length = maxByteArrayLen length = maxByteArrayLen
cbytes = mallocCBytes(v, maxByteArrayLen) cbytes = mallocCBytes(v, maxByteArrayLen)
@ -27,8 +26,6 @@ func TestBytesConverter(t *testing.T) {
if !isAll(goBytes, v) { if !isAll(goBytes, v) {
t.Errorf("incorrect value, all bytes should be %v", v) t.Errorf("incorrect value, all bytes should be %v", v)
} }
// equalBytes(t, data, goBytes)
} }
func TestConcurrentBytesConverter(t *testing.T) { func TestConcurrentBytesConverter(t *testing.T) {