gpt4 book ai didi

go - 在Go中将* _Ctype_float转换为float32

转载 作者:行者123 更新时间:2023-12-01 21:11:57 24 4
gpt4 key购买 nike

我是Go语言的新手,很难将* _Ctype_float数据类型转换为[] float32。有什么我想念的吗?我什至想到了将* _Ctype_float转换为字符串,但是那还是不成功。

我有一个名为predictInstance的C函数,该函数返回float*。我从Go by调用此函数

predictionValues := C.predictInstance(
handle,
(*C.float)(unsafe.Pointer(&req.FlatInput[0])),
)

现在,当我查看预测值的类型时,它说它是 *Ctype_float。现在我想将其转换为 []float32

最佳答案

I have a C function which returns a float* array which I wish to convert to []float32. I am calling this function from Go with a float* array argument.



一个有效的例子
package main

/*
#include <stdlib.h>
#include <float.h>

float *reverse(float *f, int len) {
float *g = calloc(len, sizeof(float));
for (int i = 0; i < len; i++) {
g[i] = f[len-1-i];
}
return g;
}
*/
import "C"

import (
"fmt"
"math"
"unsafe"
)

func main() {
a := []float32{3.14159, 2.718, 1}
r := make([]float32, len(a))
fmt.Println("a:", a, "r:", r)
c := C.reverse((*C.float)(&a[0]), C.int(len(a)))
copy(r, (*[1 << 20]float32)(unsafe.Pointer(c))[:])
C.free(unsafe.Pointer(c))
fmt.Println("a:", a, "r:", r)
}

var okCFloat = func() bool {
if C.sizeof_float != unsafe.Sizeof(float32(0)) {
panic("C float != Go float32")
}
if C.FLT_MAX != math.MaxFloat32 {
panic("C float != Go float32")
}
return true
}()

输出:
a: [3.14159 2.718 1] r: [0 0 0]
a: [3.14159 2.718 1] r: [1 2.718 3.14159]

关于go - 在Go中将* _Ctype_float转换为float32,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59222892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com