猿问

Cgo将字符串传递给C文件

我正在使用cgo并看到这篇关于从 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++ 函数?我试图通过 arune[]但它没有用。


森林海
浏览 167回答 1
1回答

RISEBY

这是Go代码:// GetFileSizeC wrapper method for retrieve byte lenght of a filefunc GetFileSizeC(filename string) int64 {&nbsp; &nbsp; // Cast a string to a 'C string'&nbsp; &nbsp; fname := C.CString(filename)&nbsp; &nbsp; defer C.free(unsafe.Pointer(fname))&nbsp; &nbsp; // get the file size of the file&nbsp; &nbsp; size := C.get_file_size(fname)&nbsp; &nbsp; return int64(size)}从 Clong get_file_size(char *filename) {&nbsp; long fsize = 0;&nbsp; FILE *fp;&nbsp; fp = fopen(filename, "r");&nbsp; if (fp) {&nbsp; &nbsp; fseek(fp, 0, SEEK_END);&nbsp; &nbsp; fsize = ftell(fp);&nbsp; &nbsp; fclose(fp);&nbsp; }&nbsp; return fsize;}请记住,您需要在 Go 文件中导入之前添加所需的头文件库:package utils// #cgo CFLAGS: -g -Wall// #include <stdio.h>&nbsp; &nbsp;|// #include <stdlib.h>&nbsp; | -> these are the necessary system header// #include <string.h>&nbsp; |// #include "cutils.h" <-- this is a custom header fileimport "C"import (&nbsp; &nbsp; "bufio"&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "io/ioutil"&nbsp; &nbsp; &nbsp;....)这是一个旧项目,您可以将其用于未来的工作示例:https://github.com/alessiosavi/GoUtils
随时随地看视频慕课网APP

相关分类

Go
我要回答