cgo Simple example of passing a goLang function to C as a callback function

Create a new folder and create a test.h file in this folder with the following content:

#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

 Create a test.c file with the following content:

#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);
}

Create a main.go file with the following content:

package main

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

Guess you like

Origin blog.csdn.net/JineD/article/details/131024802