无法在cgo中访问c变量 [英] Cannot access c variables in cgo

查看:158
本文介绍了无法在cgo中访问c变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试访问cgo中的ac结构,但是转到这个


无法确定C.utmpx


utmpx是ac struct



这里是go代码:

  / * 
#include< stdio.h>
#include< stdlib.h>
#include< utmpx.h>
#include< fcntl.h>
#include< unistd.h>
* /
导入C

类型记录C.utmpx

fd,err:= os.Open(C._PATH_UTMPX)//这可以工作
fd,err:= os.Open(C.UTMPX_FILE)//错误

在utmpx.h文件中,有

  #define _PATH_UTMPX/ var / run / utmpx
#定义UTMPX_FILE _PATH_UTMPX

我可以使用_PATH_UTMPX,但是在使用UTMPX_FILE时得到相同的警告,为什么?



看来我无法访问这些在.h文件中声明的变量
我该怎么做?

平台:macOS sirria,去1.8

解决方案

#define对于CGo是有问题的。我可以在Linux amd64上使用Go 1.8.1,像这样:

  package main 

importos

/ *
#define _GNU_SOURCE 1
#include
#include< stdlib.h>
#include< utmpx.h>
#include< fcntl.h>
#include< unistd.h>

char * path_utmpx = UTMPX_FILE;

typedef struct utmpx utmpx;
* /
导入C

类型记录C.utmpx

func main(){
path:= C.GoString (C.path_utmpx)
fd,err:= os.Open(path)
if err!= nil {
panic(bad)
}
fd .Close()
}




  1. 我必须定义_GNU_SOURCE以获得UTMPX_FILE定义。

  2. 我必须创建path_utmpx变量来解决CGo出现的#define问题。
  3. 必须执行typedef获得类型记录C.utmpx 编译。

  4. 使用Go,您不能直接使用C字符串。您必须将它们转换为Go字符串。同样,如果你想用Go字符串调用C函数,你必须将它们转换为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

解决方案

#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!

这篇关于无法在cgo中访问c变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆