duaj39673 2019-05-29 15:15
浏览 140

如何调用采用包含指针的c结构的c函数

From a GO program on a Raspberry PI I'm trying to call a function(Matlab function converted to C function) and the input to the function is a pointer to a struct and the struct contains pointer to a double(data) and a pointer to an int(size) and two int(allocatedSize, numDimensions). I have tried several ways but nothing has worked, when I have passed the compilation it usually throws a panic: runtime error: cgo argument has Go pointer to Go pointer when I run the program.

sumArray.c

/*sumArray.C*/
/* Include files */
#include "sumArray.h"

/* Function Definitions */
double sumArray(const emxArray_real_T *A1)
{
  double S1;
  int vlen;
  int k;
  vlen = A1->size[0];
  if (A1->size[0] == 0) {
    S1 = 0.0;
  } else {
    S1 = A1->data[0];
    for (k = 2; k <= vlen; k++) {
      S1 += A1->data[k - 1];
    }
  }

  return S1;
}

sumArray.h

#ifndef SUMARRAY_H
#define SUMARRAY_H

/* Include files */
#include <stddef.h>
#include <stdlib.h>
#include "sumArray_types.h"

/* Function Declarations */
extern double sumArray(const emxArray_real_T *A1);

#endif

sumArray_types.h

#ifndef SUMARRAY_TYPES_H
#define SUMARRAY_TYPES_H

/* Include files */

/* Type Definitions */
#ifndef struct_emxArray_real_T
#define struct_emxArray_real_T

struct emxArray_real_T
{
  double *data;
  int *size;
  int allocatedSize;
  int numDimensions;
};

#endif                                 /*struct_emxArray_real_T*/

#ifndef typedef_emxArray_real_T
#define typedef_emxArray_real_T

typedef struct emxArray_real_T emxArray_real_T;

#endif                                 /*typedef_emxArray_real_T*/
#endif

/* End of code generation (sumArray_types.h) */

main.go

// #cgo CFLAGS: -g -Wall
// #include <stdlib.h>
// #include "sumArray.h"
import "C"

import (
   "fmt"
)
func main() {
   a1 := [4]C.Double{1,1,1,1}
   a2 := [1]C.int{4}
   cstruct := C.emxArray_real_T{data: &a1[0], size: &a2[0]}
   cstructArr := [1]C.emxArray_real_T{cstruct}
   y := C.sumArray(&cstructArr[0])
   fmt.Print(float64(y))
}

With this example I get panic: runtime error: cgo argument has Go pointer to Go pointer when I run the program.

I do not how to make it work or if it is possible to make it work. I hope someone can help me or give some direction on how to solve this.

  • 写回答

1条回答 默认 最新

  • doubeng3412 2019-06-11 18:12
    关注

    Too much for a comment, so here's the answer.

    First, the original text:

    A direct solution is to use C.malloc(4 * C.sizeof(C.double))to allocate the array of double-s. Note that you have to make sure to call C.free() on it when done. The same applies to the second array of a single int.

    Now, your comment to the Mattanis' remark, which was, reformatted a bit:

    thanks for giving some pointers. I tried with

    a1 := [4]C.double{1,1,1,1}
    sizeA1 := C.malloc(4 * C.sizeof_double)
    cstruct := C.emxArray_real_T{
      data: &a1[0],
      size: (*C.int)(sizeA1)
    }
    y := C.sumArray(cstruct)
    defer C.free(sizeA1)
    

    but it gave me the same answer as before cgo argument has Go pointer to Go pointer when I tried to run the program

    You still seem to miss the crucial point. When you're using cgo, there are two disjoint "memory views":

    • "The Go memory" is everything allocated by the Go runtime powering your running process—on behalf of that process. This memory (most of the time, barring weird tricks) is known to the GC—which is a part of the runtime.

    • "The C memory" is memory allocated by the C code—typically by calling the libc's malloc()/realloc().

    Now imagine a not-so-far-fetched scenario:

    1. Your program runs, the C "side" gets initialized and spawns its own thread (or threads), and holds handles on them.
    2. Your Go "side" already uses multiple threads to run your goroutines.
    3. You allocate some Go memory in your Go code and pass it to the C side.
    4. The C side passes the address of that memory to one or more of its own threads.
    5. Your program continues to chug away, and so do the C-side threads—in parallel with your Go code.

    As a result you have a reasonably classical scenario in which you get a super-simple situation for unsynchronized parallel memory access, which is a sure recepy for disaster on today's multi-core multi-socket hardware.

    Also consider that Go is considerably a more higher-level programming language than C; at the bare minimum, it has automatic garbage collection, and notice that nothing in the Go spec specifies how exactly the GC must be specified. This means, a particular implementation of Go (including the reference one—in the future) is free to allow its GC to move arbitrary objects in the memory¹, and this means updating every pointer pointing into the memory block in its original location to point to the same place in the block's new location—after it was moved.

    With these considerations in mind, the Go devs postulated that in order to keep cgo-using programs future-proof², it is forbidden to pass to C any memory blocks which contain pointers to other Go memory blocks.

    It's okay to pass Go memory blocks which contain pointers to C memory, though.

    Going back to the example from your second comment, you still allocate the array of 4 doubles, a1, in the Go memory.

    Then the statement cstruct := C.emxArray_real_T{...} again allocates an instance of C.emxArray_real_T in the Go memory, and so after you initialize its data field with a pointer to Go memory (&a1[0]), and then pass its address to the C side, the runtime performs its dynamic checks before actually calling into the C side and crashes your program.


    ¹ This is typical behaviour for the so-called "generational" garbage collectors, for one example.

    ² That is, you recompile your program with a future version of the Go compiler of the same "major" release, and the program continues to work, unmodified.

    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB yalmip 可转移负荷的简单建模出错,如何解决?
  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?