cgo 将goLang函数作为回调函数传递给C的简单示例

新建一个文件夹,在该文件夹内创建 test.h 文件,内容如下:

#ifndef __TEST_H__
#define __TEST_H__
#ifdef __cplusplus
extern "C"{
#endif

#define API __attribute__((visibility("default")))

typedef struct info{
    void* a;
    int  size;
}tInfo;

typedef int(*cb) (tInfo* n);


API int setcallback(cb s);

API void call();

API void clean();

#ifdef __cplusplus
}
#endif
#endif

 创建 test.c 文件,内容如下:

#include "test.h"
#include <stdlib.h>
#include <string.h>

cb gS;
tInfo info;

int setcallback(cb s){
    gS = s;
    info.a = malloc(3);
    info.size = 3;
    char t[3] = "abc";
    memcpy(info.a, t, 3);
    return 1;
}

void call(){
    gS(&info);
}

void clean(){
    free(info.a);
}

创建 main.go 文件,内容如下:

package main

/*
#cgo CFLAGS: -I./
#cgo LDFLAGS:-Wl,-rpath,./
#cgo 

猜你喜欢

转载自blog.csdn.net/JineD/article/details/131024802