Home > Article > Backend Development > How do Golang functions interact with other languages?
Go allows interaction with other languages via CGO and external invocation (FFI). CGO is used to call C code, while FFI can be used to call functions in JavaScript, Python and other languages. For example, you can use FFI to call the Python function sum_numbers so that you can use it with Go code in JavaScript.
Go provides powerful support that allows you to use functions written in other languages without leaving your Go code. Here's how to do it:
Using CGO
CGO allows you to call C code. Here's how to use it:
// #include <stdio.h> import "C" func main() { C.printf("Hello, world!\n") }
Using External Invocation (FFI)
FFI allows you to call functions in other languages, such as JavaScript and Python. The following is how to use FFI to call JavaScript functions:
package main import ( "github.com/gopherjs/gopherjs/js" ) func main() { js.Global.Get("document").Get("getElementById").Invoke("myElement") }
Practical case: Calling Python functions
Suppose you have the following Python functions:
def sum_numbers(a, b): return a + b
You can Call this function in Go using FFI:
package main import ( "github.com/gopherjs/gopherjs/js" ) func main() { pyFunc := js.Global.Get("sum_numbers") result := pyFunc.Invoke(js.MakeWrapperType(1), js.MakeWrapperType(2)) js.Global.Get("console").Call("log", result) }
When you run this code, it will call the Python function in JavaScript and print the result.
Note:
Using FFI requires accurate knowledge of the API of the target language. There are also third-party libraries available to facilitate FFI, such as [github.com/gonum/cgo](https://github.com/gonum/cgo).
The above is the detailed content of How do Golang functions interact with other languages?. For more information, please follow other related articles on the PHP Chinese website!