Home >Backend Development >Golang >How to Access a C `const char*` Array from Go?

How to Access a C `const char*` Array from Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-26 13:40:11410browse

How to Access a C `const char*` Array from Go?

Accessing a C Array of Type const char * from Go

Problem

A C program defines an array of type const char *, named myStringArray, containing a list of strings. The goal is to access this array from a Go program using cgo and convert each array entry into a Go string.

Discussion

However, the provided Go code fails to access the array correctly, instead it iterates over the characters of the first string in the array.

Solution

A better approach is to first convert the C array into a Go slice, which provides a more convenient and safer way to access its elements. Here's how this can be done:

import "C"
import "fmt"

// Convert the C array into a Go slice of pointers to C (null-terminated) strings.
arraySize := 3
cStrings := (*[1 << 30]*C.char)(unsafe.Pointer(&C.myStringArray))[:arraySize:arraySize]

// Iterate over the slice and convert each C string into a Go string.
for _, cString := range cStrings {
    fmt.Println(C.GoString(cString))
}

Output:

NAME_OF_FIRST_THING
NAME_OF_SECOND_THING
NAME_OF_THIRD_THING

This solution ensures that each array element is accessed correctly as a distinct Go string.

The above is the detailed content of How to Access a C `const char*` Array from Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:I Make Golang libraryNext article:I Make Golang library