【问题标题】:Cgo pass a string to C fileCgo将字符串传递给C文件
【发布时间】:2020-02-20 18:30:24
【问题描述】:

我正在使用 cgo 并看到 this 关于从 go 运行 c++ 的帖子:

我想在 Go 中使用 [此功能]。我将使用C接口

  // foo.h
  #ifdef __cplusplus
  extern "C" {
  #endif
   typedef void* Foo;
   Foo FooInit(void);
   void FooFree(Foo);
   void FooBar(Foo);
  #ifdef __cplusplus
  }
  #endif

我这样做了,但是如何将字符串作为参数传递给 C++ 函数?我尝试传递 rune[],但没有成功。

【问题讨论】:

  • 我假设您的意思是像 C 中那样以 nul 结尾的字符串,而不是某些 C++ 字符串类。如果是这样,请参阅github.com/golang/go/wiki/cgo#go-strings-and-c-strings
  • 我引用了您引用的参考文献来扩展您的问题。希望对您有所帮助。

标签: go cgo


【解决方案1】:

这是Go 代码:

// GetFileSizeC wrapper method for retrieve byte lenght of a file
func GetFileSizeC(filename string) int64 {
    // Cast a string to a 'C string'
    fname := C.CString(filename)
    defer C.free(unsafe.Pointer(fname))
    // get the file size of the file
    size := C.get_file_size(fname)
    return int64(size)
}

来自 C

long get_file_size(char *filename) {
  long fsize = 0;
  FILE *fp;
  fp = fopen(filename, "r");
  if (fp) {
    fseek(fp, 0, SEEK_END);
    fsize = ftell(fp);
    fclose(fp);
  }
  return fsize;
}

记住在导入之前需要在Go文件中添加需要的头文件库:

package utils

// #cgo CFLAGS: -g -Wall
// #include <stdio.h>   |
// #include <stdlib.h>  | -> these are the necessary system header
// #include <string.h>  |
// #include "cutils.h" <-- this is a custom header file
import "C"
import (
    "bufio"
    "encoding/json"
    "fmt"
    "io/ioutil"
     ....
)

这是一个旧项目,您可以将其用于未来的工作示例:

https://github.com/alessiosavi/GoUtils

【讨论】:

  • 你为什么称它为“演员表”,它实际上是一种类型对话(包括不必要的(对于这种情况)复制)?
  • 嗨@Laevus,我不明白你的意思。为了调用C代码必须转换(你是对的,不是强制转换)字符串然后释放数据。为什么不需要副本?你能提供一个简单的测试吗?
  • 是的,抱歉,我忘记了在这种情况下字符串必须以空值结尾。在另一个中,我会从 go 的字符串中传递支持数组指针
猜你喜欢
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多