【发布时间】:2020-07-25 08:39:28
【问题描述】:
我正在尝试创建一个 C 结构点并将其传递给 Go,但我不断得到一个 nil 指针。我在 C 中有以下内容并从 Go 调用。
测试.h
#include <stdio.h>
typedef struct TestStruct {
int test_int;
} TestStruct;
TestStruct* newTestStruct();
test.c
TestStruct* newTestStruct() {
printf("[C] Creating TestStruct...\n");
TestStruct test = {0};
test.test_int = 10;
TestStruct* testPtr = &test;
if (testPtr == NULL) {
printf("[C] TestStruct is NULL.\n");
}
fflush(stdout);
return testPtr;
}
test.go
package teststruct
import "log"
// #include "test.h"
import "C"
type TestStruct C.struct_TestStruct
func NewTestStruct() *TestStruct {
t := C.newTestStruct()
if t == nil {
log.Errorf("[Go] TestStruct is nil.")
}
return (*TestStruct)(t)
}
它打印出以下内容:
[C] Creating TestStruct...
[Go] TestStruct is nil.
为什么在 Go 端是 nil?
【问题讨论】: