duanqun9740 2017-05-17 23:38
浏览 157
已采纳

无法访问CGO中的C变量

I'm trying to access a c struct in cgo, but go this

could not determine kind of name for C.utmpx

utmpx is a c struct

here is the go code:

/*
#include <stdio.h>
#include <stdlib.h>
#include <utmpx.h>
#include <fcntl.h>
#include <unistd.h>
*/
import "C"

type record C.utmpx

fd, err := os.Open(C._PATH_UTMPX) // this works
fd, err := os.Open(C.UTMPX_FILE)  // error

In the utmpx.h file , there is

 #define    _PATH_UTMPX     "/var/run/utmpx"
 #define    UTMPX_FILE  _PATH_UTMPX

I can use _PATH_UTMPX but get the same warn when using UTMPX_FILE, why?

It seems that I cannot access these variables declared in .h file How can i do this ?

platform: macOS sirria,go 1.8

  • 写回答

1条回答 默认 最新

  • duanjia6959 2017-05-18 04:18
    关注

    #define's are problematic with CGo. I could get it to work with Go 1.8.1 on Linux amd64 like this:

    package main
    
    import "os"
    
    /*
    #define _GNU_SOURCE 1
    #include <stdio.h>
    #include <stdlib.h>
    #include <utmpx.h>
    #include <fcntl.h>
    #include <unistd.h>
    
    char *path_utmpx = UTMPX_FILE;
    
    typedef struct utmpx utmpx;
    */
    import "C"
    
    type record C.utmpx
    
    func main() {
        path := C.GoString(C.path_utmpx)
        fd, err := os.Open(path)
        if err != nil {
            panic("bad")
        }
        fd.Close()
    }
    
    1. I had to define _GNU_SOURCE to get the UTMPX_FILE definition.
    2. I had to create the path_utmpx variable to get around the #define problems with CGo.
    3. I had to do the typedef to get type record C.utmpx compile.
    4. With Go, you can't use C strings directly. You must convert them to Go strings. Similarly, if you want to call C functions with Go strings, you must convert them to C strings (and free the space allocated in the heap).

    A few pointers:

    Good luck!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛