Hi,
I have CGO project.
Following is my C header file and Go code
syslog-node.h
===============
#ifndef _TEST_H_
#define _TEST_H_
#include <stdlib.h>
typedef void (*key_value_cb)(const char* key, const char* value, size_t value_len, int work);
typedef struct Foo{
key_value_cb cb;
int data;
}Foo;
int initialize_engine(const char* filename, const char* module_path, Foo *cb);
int reload_pattern_db(const char* filename, Foo *cb);
cfunc.go
========
/*
#include <stdio.h>
// The gateway function
void callOnMeGo_cgo(char *key, char *value, size_t value_len, int work)
{
void ParsedData(const char *key, const char *value, size_t value_len, int work);
ParsedData(key, value, value_len, work);
}
*/
import "C"
main.go
========
var InitStruct *C.struct_Foo;
func InitializeEngine(pattern string, path string) {
pattern_db := C.CString(pattern)
module_path := C.CString(path)
if InitStruct != nil{
C.free(unsafe.Pointer(InitStruct))
}
InitStruct := (*C.Foo)(C.calloc(1, C.sizeof_struct_Foo))
InitStruct.cb = (C.key_value_cb)(C.callOnMeGo_cgo)
InitStruct.data = C.int(0)
fmt.Println(InitStruct) <<<<<<<<<<<<<<<<<<<<<<<<<<<'&{0x4b79d0 0 [0 0 0 0]}' got printed
C.initialize_engine(pattern_db, module_path, InitStruct)
}
func ReloadPatternDB(patterndb string) {
path := C.CString(patterndb)
InitStruct = (*C.Foo)(C.calloc(1, C.sizeof_struct_Foo)) <<<<<<<Allocating a new memory
InitStruct.cb = (C.key_value_cb)(C.callOnMeGo_cgo)
InitStruct.data = C.int(0)
fmt.Println(InitStruct) <<<<<<<<<<<<<<<<<<<<<<<<<<< '&{0x4b79d0 0 [0 0 0 0]}' got printed
C.reload_pattern_db(path, InitStruct)
}
I have a Go code where I have to call C functions 'initialize_engine' and 'reload_pattern_db' respectively(one after the other ) and pass the C struct from Go code.
The issue is after allocating memory to 'InitStruct' using calloc in 'InitializeEngine' method, the same memory location is getting printed in ReloadPatternDB method even though I am allocating a new memory to 'InitStruct' using calloc in 'ReloadPatternDB' method.
1) Is this the correct way to pass a C struct from a Go code to C code.
2) Is this a correct way to free the struct memory assigned to InitStruct using calloc on Go side ?
Thanks,
Nitish