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
Release: 2024-11-26 13:40:11
Original
394 people have browsed it

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))
}
Copy after login

Output:

NAME_OF_FIRST_THING
NAME_OF_SECOND_THING
NAME_OF_THIRD_THING
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template