为了账号安全,请及时绑定邮箱和手机立即绑定

Cgo将字符串传递给C文件

Cgo将字符串传递给C文件

Go
森林海 2022-05-18 14:02:01
我正在使用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[]但它没有用。
查看完整描述

1 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

这是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


查看完整回答
反对 回复 2022-05-18
  • 1 回答
  • 0 关注
  • 166 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号