Home > Backend Development > Golang > How Can I Call Go Code from Within a C Program?

How Can I Call Go Code from Within a C Program?

DDD
Release: 2024-12-27 07:41:17
Original
957 people have browsed it

How Can I Call Go Code from Within a C Program?

Integrating Go with Existing C Projects: Calling Go Code from C

Since the release of Go 1.5, the possibility of integrating Go with existing C projects has emerged. This guide aims to address the query of how to evoke Go code from within a C program.

Go 1.5 introduced the -buildmode=c-archive option, facilitating the generation of C-callable archives. However, generating the necessary header files may pose challenges. To resolve this issue, it's crucial to mark functions as exported CGo symbols.

To illustrate, consider the following Go code in foo.go:

package main

import (
    "C"
    "fmt"
)

//export PrintInt
func PrintInt(x int) {
    fmt.Println(x)
}

func main() {}
Copy after login

To compile this code as a C-callable static library, execute the following command:

go build -buildmode=c-archive foo.go
Copy after login

This command will produce an archive (foo.a) and a header file (foo.h). The header file will contain declarations such as:

typedef long long GoInt64;
typedef GoInt64 GoInt;
extern void PrintInt(GoInt p0);
Copy after login

With these declarations, it's now possible to invoke the exported function from a C program:

#include "foo.h"

int main(int argc, char **argv) {
    PrintInt(42);
    return 0;
}
Copy after login

To compile this C program:

gcc -pthread foo.c foo.a -o foo
Copy after login

The -pthread option is necessary as the Go runtime utilizes threads. Upon execution, the program will output 42.

By following these steps, you can effectively use Go code within existing C projects, benefiting from the higher-level features of Go while maintaining the low-level access provided by C.

The above is the detailed content of How Can I Call Go Code from Within a C Program?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template