iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📑

Calling Go from C and Python

に公開
2021/05/29

Go has the ability to generate dynamic libraries, which makes it extremely useful in cases where you want to call a Go library from another programming language.
This article explains the basic usage of this feature.

Go

Source Code

main.go
package main

import "C"
import "fmt"

//export foo
func foo(name *C.char) *C.char {
	nameString := C.GoString(name)
	result := fmt.Sprintf("Hello, %s!", nameString)
	return C.CString(result)
}

func main() {}

This is the core code of the library.

By importing the C package, you can call various cgo functions and types.

Functions exported using the //export directive can be used from the shared library.

I have used *C.char for the arguments and return values because using string would cause the GoString type to be used in the shared library.
GoString is a type defined as struct { const char *p; ptrdiff_t n; }. In programming languages that cannot read header files, such as Python, handling this is a bit cumbersome—for example, you would need to define a class with a _fields_: List[Tuple] member to specify for argtypes or rettype. Therefore, I have omitted it here.
I might explain this in a separate article when I have time in the future.

Build

go build -buildmode=c-shared -o main.so main.go

C

Source Code

main.c
#include <stdio.h>
#include "main.h"

int main() {
	char* result = foo("mopeneko");
	puts(result);
}

By including main.h, which is generated when the library is built, you can call the types and exported functions generated by Go.

If you were using string, you would have to access it according to the struct definition described in main.h.

Build

cc -o main main.c main.so

Build by passing the previously built main.so to the compiler.

Execute

$ ./main
Hello, mopeneko!

Python

Source Code

main.py
from ctypes import CDLL, c_char_p

lib = CDLL("./main.so")
foo = lib.foo
foo.restype = c_char_p
print(foo(b"mopeneko").decode("utf-8"))

Since restype defaults to ctypes.c_int, you need to specify it according to the return value.

Arguments and return values are char*, which is essentially synonymous with the bytes type, so you must perform type conversion appropriately using b"" or str.decode().

As mentioned earlier, if string were used for arguments or return values, you would need to specify a class for argtypes or rettype.

Execute

$ python main.py
Hello, mopeneko!

Discussion