duanfei8897 2014-05-14 15:07
浏览 213
已采纳

通过go函数的参数返回值,该函数从C调用

Suppose, we've got a Go function, which is doing something with agruments, passed to them, e.g. it could fill the buffer, allocated in the C part and changing it and for example an integer argument, which is a size of read data. It works well with an integer one, but not with a "data part". Just see a code.

package main

/*

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>

extern int some(uint8_t *, int *);

static int somewrap() {
    uint8_t *i = malloc(16);
    int A = 1;
    int *x = &A;

    some(i, x);

    fprintf(stderr, "c.wrapper, i=%s, %p, x=%d, %p
", i, i, *x, x);

    return 0;
}

*/
import "C"

import "fmt"
import (
    "unsafe"
)

//export some
func some(i *C.uint8_t, x *C.int) C.int {
    fmt.Println("i:", i, &i, *i, "x:", x, &x, *x)

    p := []byte("xxx")
    i = (*C.uint8_t)(unsafe.Pointer(&p[0]))

    *x = C.int(42)

    fmt.Println("i:", i, &i, *i, "x:", x, &x, *x)
    return C.int(0)
}

func main() {
    C.somewrap()
}

As a result, we've got following:

i: 0x4303a40    0xc210000018 0   x: 0x7fff5fbff874 0xc210000020 1
i: 0xc210000038 0xc210000018 120 x: 0x7fff5fbff874 0xc210000020 42
c.wrapper, i=, 0x4303a40, x=42, 0x7fff5fbff874

As you can see, it works well for integer pointer, but not for uint8_t.

  • 写回答

1条回答 默认 最新

  • doupo2633 2014-05-14 16:13
    关注

    You're re-assigning i within some to another address, not change the value at the given address (unless I'm misunderstanding what you're trying to accomplish)

    *i = *(*C.uint8_t)(unsafe.Pointer(&p[0]))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘