Skip to content

Instantly share code, notes, and snippets.

@cuducos
Created February 19, 2021 15:39
Show Gist options
  • Save cuducos/4ea87d41f0ff7f5f02e6ed8fa51742f5 to your computer and use it in GitHub Desktop.
Save cuducos/4ea87d41f0ff7f5f02e6ed8fa51742f5 to your computer and use it in GitHub Desktop.
package main
func Hello() string {
return "Hello, from a Go extension!"
}
#include <stdio.h>
#include "helloc.h"
void HelloC() {
printf("Hello, from a C extension!\n");
}
#include <stdio.h>
#include <stdlib.h>
void HelloC();
package main
import (
"fmt"
"plugin"
)
type extension struct {
path string
funcName string
}
func (e *extension) load() (func() string, error) {
p, err := plugin.Open(e.path)
if err != nil {
return nil, err
}
f, err := p.Lookup(e.funcName)
if err != nil {
return nil, err
}
return f.(func() string), nil
}
func main() {
for _, e := range []extension{
{"./lib/hello.so", "Hello"},
{"./lib/helloc.so", "HelloC"},
} {
f, err := e.load()
if err != nil {
panic(err)
}
fmt.Println(fmt.Sprintf("Calling %s() from %s:\n\t%s", e.funcName, e.path, f()))
}
}
run:
@gcc helloc.c -fPIC -shared -o lib/helloc.so
@go build -o lib/hello.so -buildmode=plugin hello.go
@go run main.go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment