Skip to content

Instantly share code, notes, and snippets.

@kostix
Last active October 5, 2021 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kostix/10c80b61a32cd2f4fd2dcc6b1c317ca2 to your computer and use it in GitHub Desktop.
Save kostix/10c80b61a32cd2f4fd2dcc6b1c317ca2 to your computer and use it in GitHub Desktop.
Freeing a C resource produced by Go code
package main
/*
#include <stdlib.h>
typedef struct {
char *response;
} Resp;
*/
import "C"
import "unsafe"
//export getResponse
func getResponse() C.Resp {
// b := C.CString(Response.respBody)
// defer C.free(b)
return C.Resp{
response: C.CString("abcde"),
}
}
//export freeResponse
func freeResponse(response *C.char) {
C.free(unsafe.Pointer(response))
}
func main() {
}
$ go build -o getresp.so -buildmode=c-shared ./gocode
$ gcc -o useresp useresp.c ./getresp.so
$ ./useresp
0x0x562d23abd3d0
$ echo $?
0
#include <stdio.h>
#include "getresp.h"
int main(void)
{
Resp resp;
resp = getResponse();
printf("0x%08p\n", resp.response);
freeResponse(resp.response);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment