我正在尝试在 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)
还有。
答案 0 :(得分:-1)
如果使用C.String
//将字符串转换为C字符串// C字符串在C堆中分配 使用malloc。 //安排电话是负责人的责任 被释放,例如通过调用C.free(确保包含stdlib.h //如果需要C.free) 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)
}