Last active
January 27, 2020 19:18
-
-
Save shivamMg/15e22ccba386f0bda2ad7cfaae29b855 to your computer and use it in GitHub Desktop.
Simple example for building C Shared Libraries with Go
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 <string.h> | |
| #include <stdlib.h> | |
| #include "libhello.h" | |
| int main(int argc, char **argv) { | |
| char *name, *greeting; | |
| if (argc < 2) { | |
| fprintf(stderr, "missing name\n"); | |
| return 1; | |
| } | |
| name = strdup(argv[1]); | |
| greeting = Hello(name); | |
| free(name); | |
| printf("%s\n", greeting); | |
| return 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
| from __future__ import print_function | |
| import ctypes | |
| from os.path import abspath, dirname, join | |
| import sys | |
| if __name__ == '__main__': | |
| if len(sys.argv) < 2: | |
| print('missing name', file=sys.stderr) | |
| sys.exit(1) | |
| name = sys.argv[1] | |
| lib_path = abspath(join(dirname(__file__), 'libhello.so')) | |
| lib = ctypes.CDLL(lib_path) | |
| lib.Hello.argtypes = [ctypes.c_char_p] | |
| lib.Hello.restype = ctypes.c_char_p | |
| greeting = lib.Hello(name.encode('utf-8')) | |
| print(greeting.decode('utf-8')) |
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 | |
| import "C" | |
| //export Hello | |
| func Hello(name *C.char) *C.char { | |
| return C.CString("Hello " + C.GoString(name)) | |
| } | |
| func main() {} |
Author
shivamMg
commented
Jan 27, 2020
- http://snowsyn.net/2016/09/11/creating-shared-libraries-in-go/
- https://github.com/vladimirvivien/go-cshared-examples
- https://github.com/jima80525/ctypes_example
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment