【问题标题】:C struct is nil when return in Go在 Go 中返回时 C 结构为 nil
【发布时间】: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?

【问题讨论】:

    标签: pointers go struct cgo


    【解决方案1】:

    您正在返回一个指向 C 中堆栈分配结构的指针,这非常错误

    newTestStruct 返回的指针本质上是悬空,试图通过它访问任何数据可能会导致崩溃或更糟。

    如果要返回指向它的指针,请确保在堆上分配数据,例如:

    TestStruct* newTestStruct() {
        printf("[C] Creating TestStruct...\n");
        TestStruct* testPtr = (TestStruct*)malloc(sizeof(TestStruct));
        testPtr->test_int = 10;
    
        if (testPtr == NULL) {
            printf("[C] TestStruct is NULL.\n");
        }
    
        fflush(stdout);
        return testPtr;
    }
    

    顺便说一句,在任何半现代的 C 编译器上,您都会收到有关 C 代码的警告,例如 warning: function returns address of local variable [-Wreturn-local-addr]

    【讨论】:

      猜你喜欢
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      相关资源
      最近更新 更多