Skip to content

Instantly share code, notes, and snippets.

@shivamMg
Last active January 27, 2020 19:18
Show Gist options
  • Save shivamMg/15e22ccba386f0bda2ad7cfaae29b855 to your computer and use it in GitHub Desktop.
Save shivamMg/15e22ccba386f0bda2ad7cfaae29b855 to your computer and use it in GitHub Desktop.
Simple example for building C Shared Libraries with Go
#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;
}
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'))
package main
import "C"
//export Hello
func Hello(name *C.char) *C.char {
return C.CString("Hello " + C.GoString(name))
}
func main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment