duanmeng3476 2016-07-11 14:50
浏览 225
已采纳

在C函数中更改golang C.String变量的值

i want to get an int and string from C function. int - error code, string - the data.

Tried that way:

package main
/*
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int test(char *out){
  snprintf(out, sizeof out, "1234567890abcd");
  return 0;
}

*/
import "C"

import (
  "fmt"
  "unsafe"
)

func main() {
  foo := C.CString("")
  defer C.free(unsafe.Pointer(foo))
  C.test(foo)
  fmt.Println("Output is: "+C.GoString(foo))
}

and it almost worked.

Output is: 1234567

but should be: 1234567890abcd

I think that size of C.String passed to C function is 8. But don't know how can I extend it (fixed size <> 8) or change into dynamic.

So the question is: How should I pass that variable to C?

  • 写回答

2条回答 默认 最新

  • dongzhao1930 2016-07-12 09:50
    关注

    After a research i found a solution:

    package main
    
    
    /*
    #include <stdlib.h>
    #include <string.h>
    #include <stdio.h>
    
    int test(char *out, int len){
      snprintf(out, len, "1234567890123456789012345671`iknvcap9nv1-93hbf1-39b");
      return 0;
    
    }
    
    */
    import "C"
    
    import (
      "fmt"
      "unsafe"
    )
    
    func main() {
      buf := make([]byte, 8192)
      C.test((*C.char)(unsafe.Pointer(&buf[0])), C.int(len(buf)))
      fmt.Println(string(buf))
    }
    

    To receive 'string' from C function, i had to create a slice:

      buf := make([]byte, 8192)
    

    and pass a pointer to it:

      C.test((*C.char)(unsafe.Pointer(&buf[0])), C.int(len(buf)))
    

    Using C.String in that situation is not working.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 人大金仓下载,有人知道怎么解决吗
  • ¥15 一个小问题,本人刚入门,哪位可以help
  • ¥15 python安卓开发
  • ¥15 使用R语言GD包一直不出结果
  • ¥15 计算机微处理器与接口技术相关问题,求解答图片的这个问题,有多少个端口,端口地址和解答问题的方法和思路,不要AI作答
  • ¥15 如何根据一个截图编写对应的HTML代码
  • ¥15 stm32标准库的PID角度环
  • ¥15 ADS已经下载好了,但是DAS下载不了,一直显示这两种情况,有什么办法吗,非常急!
  • ¥100 Excel 点击发送自动跳转outlook邮件
  • ¥15 gis中用栅格计算器或加权总和后图层不显示,值也明显不对