Cgo 传递一个字符串到 C 文件
Cgo pass a string to C file
我正在使用 cgo and saw this post 关于 运行 c++ from go:
I want to use [this function] in Go. I'll use the C interface
// foo.h
#ifdef __cplusplus
extern "C" {
#endif
typedef void* Foo;
Foo FooInit(void);
void FooFree(Foo);
void FooBar(Foo);
#ifdef __cplusplus
}
#endif
我这样做了,但是 我怎样才能将字符串作为参数传递给 C++ 函数?我试图传递一个 rune[]
,但没有成功。
这是 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"
....
)
这是一个旧项目,您可以将其用于未来的工作示例:
我正在使用 cgo and saw this post 关于 运行 c++ from go:
I want to use [this function] in Go. I'll use the C interface
// foo.h #ifdef __cplusplus extern "C" { #endif typedef void* Foo; Foo FooInit(void); void FooFree(Foo); void FooBar(Foo); #ifdef __cplusplus } #endif
我这样做了,但是 我怎样才能将字符串作为参数传递给 C++ 函数?我试图传递一个 rune[]
,但没有成功。
这是 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"
....
)
这是一个旧项目,您可以将其用于未来的工作示例: