亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號