我正在尝试在 GO 中调用 C 函数。这适用于某些扩展(对于整数)。但是,存在问题 下面给出了一个最小的例子
package main
/*
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
void my_reverse(char* src, int len, char *dst){
dst = malloc(sizeof(char) * (len + 1));
printf("[c-part] src=%s\n", src);
for (int i = 0; i < len; ++i)
{
dst[i] = src[len - 1 - i];
}
dst[len] = 0;
printf("[c-part] dst=%s\n", dst);
}
void some_text(char* buffer, unsigned long long int *year){
buffer = malloc(200 * sizeof(char));
sscanf("year 2018d", "%s %16llu", buffer, year);
printf("will return (%s, %16llu)\n", buffer, *year);
}
*/
import "C"
import "unsafe"
import "fmt"
func Reverse(a string) (dst string) {
c_src := C.CString(a)
defer C.free(unsafe.Pointer(c_src))
c_len := C.int(len(a))
c_dst := C.CString(dst)
defer C.free(unsafe.Pointer(c_dst))
C.my_reverse(c_src, c_len, c_dst)
return string(*c_dst)
}
func Sometext() (dst string, year int64) {
c_dst := C.CString("")
c_year := C.ulonglong(0)
defer C.free(unsafe.Pointer(c_dst))
C.some_text(c_dst, &c_year)
return string(*c_dst), int64(c_year)
}
func main() {
fmt.Printf("[gopart] dst=%v\n\n\n", Reverse("Hello World"))
buf, year := Sometext()
fmt.Printf("received (%v, %v)\n", buf, year)
}
这是两个 c 函数,它们在 c 中分配一个新的缓冲区。 但是,我得到了输出
[c-part] src=Hello World
[c-part] dst=dlroW olleH
[gopart] dst=
will return (year, 2018)
received (, 2018)
这意味着,这些字符串在 C 中可用。但我以后永远不能在 GO 中使用这些字符串。 Go-Garbage 收集器会在我可以使用它之前删除该字符串吗?
我希望看到
[gopart] dst=dlroW olleH
received (year, 2018)
还有。
最佳答案
如果在 Go 中使用 C.String
初始化字符串,则无需在 c 中处理内存分配
// Go string to C string // The C string is allocated in the C heap using malloc. // It is the caller's responsibility to arrange for it to be // freed, such as by calling C.free (be sure to include stdlib.h // if C.free is needed). func C.CString(string) *C.char
您可以使用 c.GoString() 将 C.String 转换回 go 字符串。以下是您示例的工作代码片段。
package main
/*
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
void my_reverse(char* src, char *dst){
printf("[c-part] src=%s\n", src);
int n = strlen(src);
for (int i = 0; i < n ; ++i)
{
dst[i] = src[n - 1 - i];
}
dst[n] = 0;
printf("[c-part] dst=%s\n", dst);
}
void some_text(char* buffer, unsigned long long int *year){
sscanf("year 2018d", "%s %16llu", buffer, year);
printf("will return (%s, %16llu)\n", buffer, *year);
}
*/
import "C"
import "unsafe"
import "fmt"
func Reverse(a string) (dst string) {
c_src := C.CString(a)
defer C.free(unsafe.Pointer(c_src))
c_dst := C.CString(dst)
defer C.free(unsafe.Pointer(c_dst))
C.my_reverse(c_src, c_dst)
return C.GoString(c_dst)
}
func Sometext() (dst string, year int64) {
c_dst := C.CString("")
c_year := C.ulonglong(0)
defer C.free(unsafe.Pointer(c_dst))
C.some_text(c_dst, &c_year)
return C.GoString(c_dst), int64(c_year)
}
func main() {
fmt.Printf("[gopart] dst=%v\n\n\n", Reverse("Hello World"))
buf, year := Sometext()
fmt.Printf("received (%v, %v)\n", buf, year)
}
关于c - 从 Golang 中的 c 函数返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48241246/