dongzhuang6247 2014-02-01 19:00
浏览 228
已采纳

在Go中使用C库时,如何正确地将UTF-8编码的char数组转换为Go字符串?

I'm trying to use a C library in Go. The C.PrlFoundVmInfo_GetName function writes a UTF-8 encoded string into name with length nBufSize.

// PRL_CHAR sName[1024];
var sName [1024]C.PRL_CHAR
// PRL_UINT32 nBufSize = sizeof(sName);
var nBufSize C.PRL_UINT32 = C.PRL_UINT32(unsafe.Sizeof(sName))
ret = C.PrlFoundVmInfo_GetName(hFoundVmInfo, (*C.PRL_CHAR)(unsafe.Pointer(&sName)), &nBufSize)
// printf("VM name: %s
", sName);
var gName string = C.GoString((*C.char)(unsafe.Pointer(&sName)))
fmt.Printf("VM %d name: \"%s\"
", nBufSize, gName)

What is the proper way to declare name (and nBufSize) and how do i convert name to a Go string? The above code dosen't work as I expect. It prints:

VM 1024 name: ""
... 

C API Documentation, extract

PrlFoundVmInfo_GetName - Parameters

PRL_RESULT PrlFoundVmInfo_GetName(
  PRL_HANDLE handle, 
  PRL_STR sName, 
  PRL_UINT32_PTR pnNameBufLength
);
  • handle - A handle of type PHT_FOUND_VM_INFO identifying the container.
  • sName - [out] A pointer to a buffer that receives the name. Pass a null pointer to determine the required buffer size.
  • pnNameBufLength - [in] The size of the buffer used to receive the output data (in bytes). [out] The required buffer size if the buffer parameter contains a null pointer or if the specified buffer size is not large enough.

The full documentation is available at C API Documentation - PrlFoundVmInfo_GetName

  • 写回答

2条回答 默认 最新

  • douyun3887 2014-02-09 11:14
    关注

    This was the solution, create a byte array and make sName point to it. When it has been used use C.GoStringN to convert the content to a Go string.

    var buf = make([]byte, 1024)
    var sName C.PRL_STR = (C.PRL_STR)(unsafe.Pointer(&buf))
    var nBufSize C.PRL_UINT32 = 1024
    ret = C.PrlFoundVmInfo_GetName(*hFoundVmInfo, sName, &nBufSize)
    gName := C.GoStringN((*_Ctype_char)(unsafe.Pointer(sName)), C.int(nBufSize))
    fmt.Printf("VM %d name: \"%s\"
    ", nBufSize, gName)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化