dtmwnqng38644 2012-11-16 13:41
浏览 326
已采纳

CGO; C函数具有int指针参数,如何传递正确的类型?

Currently I'm using Cgo to call C functions from Go. I'm trying to recreate the 'Read a Photo' example in Go.

One on the C functions, however, expects a int* len argument (bonus question; is that the same as int *len?). As I read this, this is a pointer to an integer. The function in question is ccv_write of the libccv library. It's full signature is:

int ccv_write(ccv_dense_matrix_t* mat, char* out, int* len, int type, void* conf)

The relevant code snippet is as follows:

type Image struct {
    image *C.ccv_dense_matrix_t
}

func main() {
    image := new(Image)

    /* ... snip ... */

    dst := C.CString("black_and_white_painting.jpg")
    defer C.free(unsafe.Pointer(dst))
    x := 0 // <- perhaps var x int ?
    C.ccv_write(image.image, dst, (*C.int)(&x), C.CCV_IO_PNG_FILE, 0)
}

The above example generates the following compile time error: cannot convert &x (type *int) to type *_Ctype_int

Any thoughts on how to pass the correct argument?

  • 写回答

3条回答 默认 最新

  • dsafgdafgdf45345 2012-11-16 17:38
    关注

    The issue here is you have two different types. You have an int which is defined by your Go compiler and C.int which is defined by your C compiler. Depending on the compilers and architecture these may be the same size. However, it is very possible that int will be 64 bits in size and C.int would be 32 bits.

    In order for the compiler to enforce the type safety, it requires you to do an explicit conversion or define the type at initialization.

    In your example, you do: x := 0. This is the same as x := int(0). The int is implied. Instead, you can do x := C.int(0).

    However, I think the "cleaner" method would be to do what jnml recommended: var x C.int. This does exactly the same thing but just looks nicer.


    Later, you will most likely want to convert that C.int back to an int. This is easy to do with a conversion.

    y := int(x)
    

    This will convert x to an int and then copy that value into the newly initialized variable y.


    Bonus Anwser: int* len is indeed the same as int *len

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

报告相同问题?

悬赏问题

  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行