Last active
October 5, 2021 14:56
-
-
Save kostix/10c80b61a32cd2f4fd2dcc6b1c317ca2 to your computer and use it in GitHub Desktop.
Freeing a C resource produced by Go code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() { | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ go build -o getresp.so -buildmode=c-shared ./gocode | |
$ gcc -o useresp useresp.c ./getresp.so | |
$ ./useresp | |
0x0x562d23abd3d0 | |
$ echo $? | |
0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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