### c-for-go Manifest Example Source: https://github.com/xlab/c-for-go/wiki/Top-5-reasons-to-use-bindings An example of a c-for-go manifest file written in YAML. This file defines how C libraries are translated into Go bindings, specifying naming conventions and method signatures, including decisions on argument types like slices versus pointers. ```yaml # Example c-for-go manifest structure # This is a conceptual representation based on the text. # Specific syntax would depend on the actual c-for-go tool. package: "vorbis" headers: - "vorbis/codec.h" - "vorbis/vorbisfile.h" # Define how C functions map to Go functions functions: # Example: A function that might take a pointer to a struct # C signature: int process_data(VorbisState* state, void* buffer, int size) process_data: go_name: "ProcessData" params: - name: "state" type: "*VorbisState" - name: "buffer" type: "[]byte" return_type: "int" # Example: A function that might take a slice or array # C signature: void set_config(Config* cfg, const char* key, const char* value) set_config: go_name: "SetConfig" params: - name: "cfg" type: "*Config" - name: "key" type: "string" - name: "value" type: "string" return_type: "void" # Define C structs and their Go equivalents structs: VorbisState: fields: # ... fields from C struct ... Config: fields: # ... fields from C struct ... # Options for binding generation options: # Decide if arguments should be slices or pointers # Example: Treat C arrays as Go slices by default default_array_to_slice: true # Example: Explicitly map a C pointer to a Go pointer explicit_pointer_types: VorbisState: "*VorbisState" ``` -------------------------------- ### TRANSLATOR Configuration Example Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section An example of the TRANSLATOR configuration manifest in YAML format, showing various settings like string handling and rule definitions for C-to-Go translation. ```yaml TRANSLATOR: ConstCharIsString: true ConstUCharIsString: false ConstRules: defines: eval PtrTips: function: - {target: "vorbis_synthesis_pcmout$", tips: [ref,arr]} - {target: ^vorbis_, tips: [ref,ref,ref]} - {target: ^ogg_, self: arr, tips: [ref,ref]} Rules: global: - {transform: lower} - {action: accept, from: "^vorbis_"} - {action: accept, from: "^ogg_"} - {action: replace, from: "^vorbis_", to: _} - {transform: export} const: - {action: accept, from: "^OV_"} - {action: replace, from: "^ov_", to: _} type: - {action: replace, from: "_t$"} private: - {transform: unexport} post-global: - {action: doc, from: "^ogg_u?int[0-9]+_t"} # types like ogg_uint32_t - {action: doc, from: "^ogg_", to: "https://xiph.org/ogg/doc/libogg/$name.html"} - {action: doc, from: "^vorbis_", to: "https://xiph.org/vorbis/doc/libvorbis/$name.html"} - {action: replace, from: _$} - {load: snakecase} ``` -------------------------------- ### YAML Rule Configuration Examples Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Provides examples of YAML configurations for defining translation rules. These examples demonstrate 'accept' and 'replace' actions with regular expressions for matching and transforming C identifiers. ```yaml Rules: global: - {action: accept, from: "^vorbis_"} - {action: accept, from: "^ogg_"} const: - {action: accept, from: "^OV_"} - {action: accept, from: "(?i)^(vpx|vp8|vp9)"} global: - {action: replace, from: "^vorbis_", to: _} - {action: replace, from: "^ov_", to: _} - {action: replace, from: "_t$"} function: - {action: replace, from: PFN_vkDebugReportCallback, to: DebugReportCallbackFunc} ``` -------------------------------- ### Install c-for-go Source: https://github.com/xlab/c-for-go/blob/master/README.md Installs the c-for-go command-line tool using Go's package management. This command makes the c-for-go generator available in your system's PATH. ```bash go install github.com/xlab/c-for-go@latest ``` -------------------------------- ### YAML Tip Specification Example Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section A real-world example in YAML showing how the `TipSpec` structure is applied. It maps regular expressions targeting specific structs (e.g., VkGraphicsPipelineCreateInfo) and functions (e.g., ^callVkEnumeratePhysicalDevices$) to corresponding tip arrays. This configuration illustrates the practical application of the tip specification system. ```yaml PtrTips: struct: - {target: VkGraphicsPipelineCreateInfo, tips: [0,0,0,0,arr,ref,ref,ref,ref,ref,ref,ref,ref,ref]} - {target: VkInstanceCreateInfo, tips: [0,0,0,ref]} function: - {target: ^callVkEnumeratePhysicalDevices$, tips: [0,ref,arr]} - {target: ^callVkGetPhysicalDeviceQueueFamilyProperties$, tips: [0,ref,arr]} - {target: ^callVkEnumerateInstanceExtensionProperties$, tips: [0,ref,arr]} - {target: ^callVkEnumerateDeviceExtensionProperties$, tips: [0,0,ref,arr]} - {target: ^callVkEnumerateInstanceLayerProperties$, tips: [ref,arr]} - {target: ^callVkEnumerateDeviceLayerProperties$, tips: [0,ref,arr]} - {target: ^callVkQueueSubmit$, tips: [0,size,arr]} - {target: ^callVkFlushMappedMemoryRanges$, tips: [0,size,arr]} - {target: ^callVkInvalidateMappedMemoryRanges$, tips: [0,size,arr]} - {target: ^callVkGetImageSparseMemoryRequirements$, tips: [0,0,size,arr]} - {target: ^callVkGetPhysicalDeviceSparseImageFormatProperties$, tips: [0,0,0,0,0,0,size,arr]} - {target: ^callVkQueueBindSparse$, tips: [0,size,arr]} - {target: ^callVkResetFences$, tips: [0,size,arr]} - {target: ^callVkWaitForFences$, tips: [0,size,arr]} - {target: ^callVkMergePipelineCaches$, tips: [0,0,size,arr]} - {target: ^callVkCreateGraphicsPipelines$, tips: [0,0,size,arr,ref,arr]} - {target: ^callVkCreateComputePipelines$, tips: [0,0,size,arr,ref,arr]} - {target: ^callVkUpdateDescriptorSets$, tips: [0,size,arr,size,arr]} - {target: ^callVkAllocateCommandBuffers$, tips: [0,ref,arr]} - {target: ^callVkFreeCommandBuffers$, tips: [0,0,size,arr]} - {target: ^callVkMapMemory, tips: [0,0,0,0,0,ref]} - {target: ^callVkCmdSetViewport$, tips: [0,0,size,arr]} - {target: ^callVkCmdSetScissor$, tips: [0,0,size,arr]} - {target: ^callVkCmdBindDescriptorSets$, tips: [0,0,0,0,size,arr,size,arr]} - {target: ^callVkCmdBindVertexBuffers$, tips: [0,0,size2,arr,arr]} - {target: ^callVkCmdCopyBuffer$, tips: [0,0,0,size,arr]} - {target: ^callVkCmdCopyImage$, tips: [0,0,0,0,0,size,arr]} - {target: ^callVkCmdBlitImage$, tips: [0,0,0,0,0,size,arr]} - {target: ^callVkCmdCopyBufferToImage$, tips: [0,0,0,0,size,arr]} - {target: ^callVkCmdCopyImageToBuffer$, tips: [0,0,0,0,size,arr]} - {target: ^callVkCmdClearColorImage$, tips: [0,0,0,ref,size,arr]} - {target: ^callVkCmdClearDepthStencilImage$, tips: [0,0,0,ref,size,arr]} - {target: ^callVkCmdClearAttachments$, tips: [0,size,arr,size,arr]} - {target: ^callVkCmdResolveImage$, tips: [0,0,0,0,0,size,arr]} - {target: ^callVkCmdWaitEvents$, tips: [0,size,arr,0,0,size,arr,size,arr,size,arr]} - {target: ^callVkCmdPipelineBarrier$, tips: [0,0,0,0,size,arr,size,arr,size,arr]} - {target: ^callVkCmdExecuteCommands$, tips: [0,size,arr]} - {target: ^callVkGetPhysicalDeviceSurfaceFormatsKHR$, tips: [0,0,ref,arr]} - {target: ^callVkGetPhysicalDeviceSurfacePresentModesKHR$, tips: [0,0,ref,arr]} - {target: ^callVkGetSwapchainImagesKHR$, tips: [0,0,ref,arr]} - {target: ^callVkGetPhysicalDeviceDisplayPropertiesKHR$, tips: [0,ref,arr]} - {target: ^callVkGetPhysicalDeviceDisplayPlanePropertiesKHR$, tips: [0,ref,arr]} - {target: ^callVkGetDisplayPlaneSupportedDisplaysKHR$, tips: [0,0,ref,arr]} - {target: ^callVkGetDisplayModePropertiesKHR$, tips: [0,0,ref,arr]} - {target: ^callVkCreateSharedSwapchainsKHR$, tips: [0,size,arr,ref,ref]} # this covers all other cases - {target: ^callVk, tips: [sref,sref,sref,sref,sref,sref,sref,sref]} ``` -------------------------------- ### PARSER Configuration Example Source: https://github.com/xlab/c-for-go/wiki/Parser-config-section Demonstrates the basic structure of the PARSER configuration block in YAML, specifying include and source paths for C header file parsing. ```yaml PARSER: IncludePaths: ["/usr/include"] SourcesPaths: ["vorbis/ogg/ogg.h", "vorbis/vorbis/codec.h"] ``` -------------------------------- ### Generator Configuration Example Source: https://github.com/xlab/c-for-go/wiki/Generator-config-section An example of the GENERATOR section in a c-for-go configuration manifest, demonstrating various settings for code generation. ```yaml GENERATOR: PackageName: vorbis PackageDescription: "Package vorbis provides Go bindings for OggVorbis implementation by the Xiph.Org Foundation" PackageLicense: "THE AUTOGENERATED LICENSE. ALL THE RIGHTS ARE RESERVED BY ROBOTS." PkgConfigOpts: [ogg, vorbis] Includes: ["ogg/ogg.h", "vorbis/codec.h"] Options: SafeStrings: true ``` -------------------------------- ### Go Struct and Function Declarations with Doc Links Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Provides Go code examples for data structures and functions, with comments linking to their original C declarations and external documentation pages. ```go // OggSyncState as declared in https://xiph.org/ogg/doc/libogg/ogg_sync_state.html type OggSyncState struct { // omitted } // Block as declared in https://xiph.org/vorbis/doc/libvorbis/vorbis_block.html type Block struct { // omitted } // OggStreamPacketin function as declared in https://xiph.org/ogg/doc/libogg/ogg_stream_packetin.html func OggStreamPacketin(os *OggStreamState, op *OggPacket) int32 { // omitted } ``` -------------------------------- ### Arch Configuration Example (ARM) Source: https://github.com/xlab/c-for-go/wiki/Parser-config-section Illustrates the C preprocessor defines that might be generated when the 'arm' architecture is specified for parsing. ```c #define __ARM_EABI__ 1 #define __arm__ 1 ``` -------------------------------- ### Transform Pipeline Example Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Demonstrates a sequence of transforms applied to normalize names, including specific 'from' filters and a general 'export' transform. ```yaml - {transform: title, from: "_partitions"} - {transform: title, from: "_resilient"} - {transform: title, from: "_error"} - {transform: export} ``` -------------------------------- ### Go Code for Size Determination Source: https://github.com/xlab/c-for-go/wiki/Parser-config-section Example Go code demonstrating how to dynamically determine sizes of C types like pointers at compile time, which can be useful when working with C interop. ```go package main import ( "unsafe" "xlab/c-for-go/pkg/ctypes" ) // Assuming C.MDB_env is a defined C struct const sizeOfEnvValue = unsafe.Sizeof([1]ctypes.MDB_env{}) const sizeOfPtr = unsafe.Sizeof(&struct{}{}) func main() { const m = 0x7fffffff // Example usage of pointer arithmetic and type casting // ptr1 := (*(*[m / sizeOfPtr]*C.char)(unsafe.Pointer(ptr0)))[i0] } ``` -------------------------------- ### ConstRules Configuration Example Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Example configuration for `ConstRules`, specifying how constants defined in C (`#define`) or enumerations (`enum`) should be unfolded into Go constants, using methods like `eval`, `cgo`, or `expand`. ```yaml ConstRules: defines: expand enum: cgo ``` -------------------------------- ### Documentation Source Rules Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Shows how to configure documentation sources using the 'doc' action, specifying target entities with 'from' filters and output templates with 'to'. Includes examples for specific prefixes and external documentation links. ```yaml Rules: post-global: - {action: doc, from: "^ogg_u?int[0-9]+_t"} # types like ogg_uint32_t - {action: doc, from: "^ogg_", to: "https://xiph.org/ogg/doc/libogg/$name.html"} - {action: doc, from: "^vorbis_", to: "https://xiph.org/vorbis/doc/libvorbis/$name.html"} ``` -------------------------------- ### Replace Rule Examples Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Illustrates the 'replace' rule type, used for substring transformations in the replace/transform pipeline. Rules are applied sequentially, allowing for prefix cutting, suffix removal, and renaming. ```APIDOC Replace Rules: - Action: 'replace' Description: Transforms identifiers by replacing substrings based on 'from' and 'to' fields. If 'to' is empty, the 'from' substring is removed. Example (global scope): Rules: global: - {action: replace, from: "^vorbis_", to: "_"} # Cuts prefix, replaces with underscore - {action: replace, from: "^ov_", to: "_"} # Cuts prefix, replaces with underscore - {action: replace, from: "_t$"} # Cuts suffix '_t' Explanation: These rules modify names by removing specific prefixes and suffixes. - Action: 'replace' Description: Renames specific functions by replacing their original C name with a new Go name. Example (function scope): Rules: function: - {action: replace, from: PFN_vkDebugReportCallback, to: DebugReportCallbackFunc} Explanation: Renames the function 'PFN_vkDebugReportCallback' to 'DebugReportCallbackFunc'. ``` -------------------------------- ### Translator: Name and Type Conversion Examples Source: https://github.com/xlab/c-for-go/wiki/Design-decisions Illustrates the name and type conversion capabilities of the translator module. It handles transformations from C-style naming conventions to Go conventions and converts various C pointer and array types into their Go equivalents. ```Go func (t *Translator) convertName(name string) string { // Converts "stuff_like_this_id()" to "StuffLikeThisID()" return convertToGoStyle(name) } func (t *Translator) convertType(cType string) string { // Converts "unsigned char *" to "[]byte" if cType == "unsigned char *" { return "[]byte" } // Converts "MyClass **" to "**MyClass" or "[]*MyClass" if strings.HasSuffix(cType, " **") { baseType := strings.TrimSuffix(cType, " **") return "[]*" + baseType // Example conversion } return cType } ``` -------------------------------- ### C Pointer Translation Tips (PtrTips) Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Demonstrates how different PtrTips ('ref', 'arr', 'sref') translate C pointer types into their Go equivalents. These examples illustrate the transformation for double and triple pointers. ```APIDOC PtrTips: - ref: Translates C pointers to Go pointers or slices of pointers. - arr: Translates C pointers to Go slices, using special unpack/pack conversions. - sref: Handles multiple pointer cases, often for pointer-to-pointer scenarios. Examples: C Type | Hint | Go Equivalent ---------|------|--------------- `Object**` | ref | `[]*Object` `Object**` | arr | `[][]Object` `Object**` | sref | `**Object` `Object***`| ref | `[][]*Object` `Object***`| arr | `[][][]Object` `Object***`| sref | `***Object` Supported Scopes: - `function`: For function arguments or return values. - `struct`: For struct fields. - `any`: For any name matching a pattern. ``` -------------------------------- ### API Documentation: Go Type Declarations with External Links Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Provides examples of Go type and function declarations that include comments linking to external documentation sources, demonstrating how to associate C entities with their online API references. ```APIDOC Go Type/Function Documentation: - OggSyncState: Description: Represents the OggSyncState structure. Declaration Source: https://xiph.org/ogg/doc/libogg/ogg_sync_state.html Go Declaration: type OggSyncState struct { ... } - Block: Description: Represents the Block structure. Declaration Source: https://xiph.org/vorbis/doc/libvorbis/vorbis_block.html Go Declaration: type Block struct { ... } - OggStreamPacketin: Description: Function to packetize data into an Ogg stream. Declaration Source: https://xiph.org/ogg/doc/libogg/ogg_stream_packetin.html Go Signature: func OggStreamPacketin(os *OggStreamState, op *OggPacket) int32 ``` -------------------------------- ### Accept/Reject Rule Examples Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Demonstrates the 'accept' and 'reject' rule types, which use regular expressions to match C names and determine whether to include or ignore them in the translation process. By default, all names are ignored. ```APIDOC Accept/Reject Rules: - Action: 'accept' Description: Includes the C identifier if its name matches the 'from' pattern. Example (global scope): Rules: global: - {action: accept, from: "^vorbis_"} - {action: accept, from: "^ogg_"} Explanation: Accepts any name starting with 'vorbis_' or 'ogg_'. - Action: 'accept' Description: Accepts constants whose names match specific patterns, case-insensitively for some. Example (const scope): Rules: const: - {action: accept, from: "^OV_"} - {action: accept, from: "(?i)^(vpx|vp8|vp9)"} Explanation: Accepts constants starting with 'OV_' or case-insensitively with 'vpx', 'vp8', 'vp9'. ``` -------------------------------- ### YAML Rule Configuration with Preset Loading Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section An example of a YAML rule configuration that uses a 'load' directive to include a predefined preset like 'snakecase', combined with other actions like 'replace'. ```yaml Rules: post-global: - {action: replace, from: _$} - {load: snakecase} ``` -------------------------------- ### TypeTips Configuration Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Specifies translation tips to help distinguish between C plain types and named types, particularly useful for complex nested typedefs. Tips can guide the translation process by identifying specific type characteristics. ```APIDOC TypeTips: # Configuration for function parameter type translation tips. # Each entry targets specific C functions using regular expressions. # 'tips' specifies the type hint for parameters (e.g., 'plain', integer index). # 'self' can be used for the type of the receiver itself. function: - {target: ^glBindAttribLocation$, tips: [0,0,plain]} - {target: ^glGetAttribLocation$, tips: [0,plain]} - {target: ^glGetUniformLocation$, tips: [0,plain]} - {target: ^glGetProgramInfoLog$, tips: [0,0,0,plain]} - {target: ^glShaderSource$, tips: [0,0,plain,0]} - {target: ^glGetString$, self: plain} # Example of how TypeTips might be structured for API documentation. # This section is illustrative of the configuration format. # Parameters: # target: Regular expression to match function names. # tips: List of type hints for function parameters (e.g., 'plain', integer index). # self: Type hint for the receiver of a method. # Returns: # Implicitly guides the C-to-Go type translation process. ``` -------------------------------- ### Eval Constant Unfolding Example Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Go code generated by the `eval` constant unfolding method. It shows how C constants and enum values are translated, including type casting and handling of potentially complex expressions. ```go const ( // LodClampNone as defined in vulkan/vulkan.h:95 LodClampNone = 1000 // RemainingMipLevels as defined in vulkan/vulkan.h:96 RemainingMipLevels = 4294967295 // WholeSize as defined in vulkan/vulkan.h:98 WholeSize = 18446744073709551615 ) // Result enumeration from https://www.khronos.org/registry/vulkan/specs/1.0/man/html/VkResult.html const ( Success Result = iota NotReady Result = 1 Timeout Result = 2 ) const ( // PaNoDevice as defined in portaudio/portaudio.h:169 PaNoDevice = -1 // PaFloat32 as defined in portaudio/portaudio.h:436 PaFloat32 = ((SampleFormat)(0x00000001)) // PaInt16 as defined in portaudio/portaudio.h:439 PaInt16 = ((SampleFormat)(0x00000008)) ) ``` -------------------------------- ### Running c-for-go Generator Source: https://github.com/xlab/c-for-go/wiki/Design-decisions This command initiates the c-for-go code generation process. It takes a project manifest file as input, which configures how C headers should be translated into Go bindings. The output is typically placed in a directory named after the Go package. ```bash c-for-go foobar.yml ``` -------------------------------- ### Build Go Project Source: https://github.com/xlab/c-for-go/wiki/Makefile-template This target navigates into the `foobar` directory and builds the Go project using `go build`. It's used to compile and verify the generated Go code. ```shell test: cd foobar && go build ``` -------------------------------- ### Main Executable: Post-Generation Formatting Source: https://github.com/xlab/c-for-go/wiki/Design-decisions Demonstrates the main executable's role in formatting generated Go code using the 'imports.Process' function. This step ensures code adheres to Go formatting standards and manages import paths. ```Go import ( "fmt" "golang.org/x/tools/imports" ) func (m *MainExecutable) finalizeCode(generatedCode string) (string, error) { // Formats the code using imports.Process after generation formattedCode, err := imports.Process("output.go", []byte(generatedCode), &imports.Options{ FormatOnly: false, // Other options can be set here }) if err != nil { return "", fmt.Errorf("failed to format code: %w", err) } return string(formattedCode), nil } ``` -------------------------------- ### Run c-for-go Build Source: https://github.com/xlab/c-for-go/wiki/Makefile-template This target executes the `c-for-go` tool with a specified YAML configuration file (`foobar.yml`). It's the primary command to initiate the code generation process. ```makefile all: c-for-go foobar.yml ``` -------------------------------- ### Go Bindings for PortAudio Source: https://github.com/xlab/c-for-go/wiki/Examples Package portaudio provides Go bindings for PortAudio, a cross-platform audio I/O library. It allows applications to play and record audio through various hardware devices. ```go # Project: github.com/xlab/portaudio-go # Manifest: portaudio.yml # Description: Go bindings for PortAudio. # Link: https://github.com/xlab/portaudio-go # Note: The actual content of portaudio.yml is not provided, but it defines the Go bindings for PortAudio. ``` -------------------------------- ### Go Bindings for PortMIDI Source: https://github.com/xlab/c-for-go/wiki/Examples Package portmidi provides Go bindings for PortMIDI, part of the PortMedia libraries. It offers a cross-platform API for MIDI input and output. ```go # Project: github.com/xlab/portmidi # Manifest: pm.yml # Description: Go bindings for PortMIDI. # Link: https://github.com/xlab/portmidi # Note: The actual content of pm.yml is not provided, but it defines the Go bindings for PortMIDI. ``` -------------------------------- ### Go Bindings for GLFW Source: https://github.com/xlab/c-for-go/wiki/Examples Package glfw provides Go bindings for GLFW, a multi-platform library essential for OpenGL, OpenGL ES, and Vulkan development. It handles window creation, input, and context management. ```go # Project: github.com/golang-ui/glfw # Manifest: glfw.yml # Description: Go bindings for GLFW. # Link: https://github.com/golang-ui/glfw # Note: The actual content of glfw.yml is not provided, but it defines the Go bindings for GLFW. ``` -------------------------------- ### Go Decoder Package for Ogg/Vorbis Source: https://github.com/xlab/c-for-go/wiki/Top-5-reasons-to-use-bindings Illustrates the creation of a Go package that abstracts a low-level C library (like Ogg/Vorbis) into a more idiomatic Go interface. This package operates on byte streams and produces sample streams, simplifying usage for Go developers. ```go // This is a conceptual Go code snippet representing the described decoder package. // It demonstrates operating on byte streams and producing sample streams. package decoder import ( "io" "bytes" "fmt" ) // Sample represents a single audio sample. type Sample float32 // SampleStream is an interface for reading audio samples. type SampleStream interface { io.Reader Samples() []Sample SampleRate() int Channels() int } // vorbisDecoder is a hypothetical implementation of SampleStream. type vorbisDecoder struct { // Internal state for Ogg/Vorbis decoding (e.g., C bindings) // cState *C.vorbis_state // Example C pointer // Buffer for raw bytes read from input byteBuffer *bytes.Buffer // Buffer for decoded samples sampleBuffer []Sample sampleRate int channels int } // NewVorbisDecoder creates a new decoder from an io.Reader. // It would internally use C bindings to decode Ogg/Vorbis data. func NewVorbisDecoder(r io.Reader) (SampleStream, error) { // In a real scenario, this would initialize C structures and bindings. // For demonstration, we simulate the setup. // Read initial data to check format (conceptual) initialData := make([]byte, 1024) // Read some header data n, err := r.Read(initialData) if err != nil && err != io.EOF { return nil, fmt.Errorf("failed to read initial data: %w", err) } // Simulate successful Ogg/Vorbis header parsing and decoder initialization // This is where C library calls would happen. // Example: C.vorbis_decode_init(cState, initialData[:n]) return &vorbisDecoder{ byteBuffer: bytes.NewBuffer(nil), // Initialize empty byte buffer sampleBuffer: make([]Sample, 0, 1024), // Pre-allocate some capacity sampleRate: 44100, // Example sample rate channels: 2, // Example channels }, nil } // Read decodes audio data into the provided byte slice. // It reads from the underlying reader, decodes, and returns samples. func (vd *vorbisDecoder) Read(p []byte) (n int, err error) { // This method would typically: // 1. Read more compressed data from the underlying reader (vd.r). // 2. Feed compressed data to the C decoder. // 3. Retrieve decoded PCM samples from the C decoder. // 4. Convert C samples to Go Samples and populate vd.sampleBuffer. // 5. Copy samples from vd.sampleBuffer to the provided slice 'p' (after conversion to bytes). // 6. Handle buffer management and EOF conditions. // Placeholder for actual decoding logic: // For demonstration, let's simulate returning some dummy data. if len(vd.sampleBuffer) == 0 { // Simulate decoding a block of audio for i := 0; i < 1024; i++ { vd.sampleBuffer = append(vd.sampleBuffer, Sample(float32(i%256)/255.0)) } } // Convert samples to bytes and copy to p bytesPerSample := 4 // Assuming float32 copyLen := 0 for i := 0; i < len(p)/bytesPerSample && len(vd.sampleBuffer) > 0; i++ { sample := vd.sampleBuffer[0] vd.sampleBuffer = vd.sampleBuffer[1:] // Convert Sample (float32) to bytes and write to p // This requires careful handling of endianness and float representation // For simplicity, we'll just write a placeholder byte pattern // In reality, you'd use binary.LittleEndian.PutUint32 or similar bytePattern := uint32(sample * 32767.0) // Scale for 16-bit PCM example p[i*bytesPerSample] = byte(bytePattern) p[i*bytesPerSample+1] = byte(bytePattern >> 8) p[i*bytesPerSample+2] = byte(bytePattern >> 16) p[i*bytesPerSample+3] = byte(bytePattern >> 24) copyLen += bytesPerSample } if copyLen == 0 && len(vd.sampleBuffer) == 0 { return 0, io.EOF // No more samples to decode } return copyLen, nil } // Samples returns the decoded audio samples. func (vd *vorbisDecoder) Samples() []Sample { // This might return a snapshot or a view of the internal sample buffer. // Depending on design, it might be cleared after reading. return vd.sampleBuffer } // SampleRate returns the audio sample rate. func (vd *vorbisDecoder) SampleRate() int { return vd.sampleRate } // Channels returns the number of audio channels. func (vd *vorbisDecoder) Channels() int { return vd.channels } ``` -------------------------------- ### Go Bindings for Vulkan API Source: https://github.com/xlab/c-for-go/wiki/Examples Package vulkan provides Go bindings for Vulkan, a low-overhead, cross-platform 3D graphics and compute API. It enables high-performance graphics and parallel computation. ```go # Project: github.com/vulkan-go/vulkan # Manifest: vulkan.yml # Description: Go bindings for Vulkan API. # Link: https://github.com/vulkan-go/vulkan # Note: The actual content of vulkan.yml is not provided, but it defines the Go bindings for Vulkan. ``` -------------------------------- ### Makefile for c-for-go Project Source: https://github.com/xlab/c-for-go/wiki/Design-decisions A sample Makefile structure for managing the c-for-go generation process. It includes targets for running the generator and cleaning the generated code, streamlining project workflows. ```makefile # Example Makefile structure GENERATOR=c-for-go MANIFEST=foobar.yml all: generate generate: $(GENERATOR) $(MANIFEST) clean: # Commands to clean generated files (e.g., rm -rf foobar/*.go) @echo "Cleaning generated files..." ``` -------------------------------- ### API Documentation: C-to-Go Transformation Actions Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Details the available actions for transforming C code elements during the C-to-Go conversion process. Includes 'transform', 'doc', 'accept', 'ignore', 'replace', and 'load' actions with their parameters and typical usage. ```APIDOC Transform Actions: - transform: Applies a name transformation (e.g., lower, title, export, unexport, upper). Parameters: - name: The name of the transform to apply (e.g., 'lower', 'title'). - from: (Optional) A regex to filter which names the transform applies to. - doc: Configures documentation source for an entity. Parameters: - from: (Optional) A regex to select target entities. - to: A template string for the documentation URL or path. Supports variables like $path, $file, $line, $name, $goname. - accept: Marks an entity to be included in the conversion. Parameters: - from: A regex to match entities to accept. - ignore: Marks an entity to be excluded from the conversion. Parameters: - from: A regex to match entities to ignore. - replace: Replaces a part of the entity name. Parameters: - from: A regex pattern to find. - to: The replacement string. Supports capture groups like $1. - transform: (Optional) A transform to apply to the replacement string. - load: Loads a predefined set of rules (preset). Parameters: - name: The name of the preset to load (e.g., 'snakecase', 'doc.file'). ``` -------------------------------- ### Go Bindings for Nuklear.h GUI Library Source: https://github.com/xlab/c-for-go/wiki/Examples Package nk provides Golang bindings for nuklear.h, a small, lightweight, and fast ANSI C GUI library. It's suitable for embedding into applications requiring a simple graphical interface. ```go # Project: github.com/golang-ui/nuklear # Manifest: nk.yml # Description: Golang bindings for nuklear.h GUI library. # Link: https://github.com/golang-ui/nuklear # Note: The actual content of nk.yml is not provided, but it defines the Go bindings for Nuklear. ``` -------------------------------- ### Go Constants for C Expansion Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Defines Go constants, including Vulkan and PortAudio values, demonstrating the translation of C constants into Go. This includes using iota for enumerations and direct assignments for specific values. ```go const ( // LodClampNone as defined in vulkan/vulkan.h:95 LodClampNone = 1000.0 // RemainingMipLevels as defined in vulkan/vulkan.h:96 RemainingMipLevels = (^uint32(0)) // WholeSize as defined in vulkan/vulkan.h:98 WholeSize = (^uint64(0)) ) // Result enumeration from https://www.khronos.org/registry/vulkan/specs/1.0/man/html/VkResult.html const ( Success Result = iota NotReady Result = 1 Timeout Result = 2 ) const ( // PaNoDevice as defined in portaudio/portaudio.h:169 PaNoDevice = ((DeviceIndex)(-1)) // PaFloat32 as defined in portaudio/portaudio.h:436 PaFloat32 = ((SampleFormat)(0x00000001)) // PaInt16 as defined in portaudio/portaudio.h:439 PaInt16 = ((SampleFormat)(0x00000008)) ) ``` -------------------------------- ### Go Bindings for CMU Pocketsphinx Source: https://github.com/xlab/c-for-go/wiki/Examples Package pocketsphinx provides Go bindings for pocketsphinx, an open-source speech recognition engine from Carnegie Mellon University. It enables continuous speech recognition in Go applications. ```go # Project: github.com/xlab/pocketsphinx-go # Manifest: pocketsphinx.yml # Description: Go bindings for CMU Pocketsphinx speech recognition engine. # Link: https://github.com/xlab/pocketsphinx-go # Note: The actual content of pocketsphinx.yml is not provided, but it defines the Go bindings for Pocketsphinx. ``` -------------------------------- ### Go Bindings for EGL API Source: https://github.com/xlab/c-for-go/wiki/Examples Package egl provides Go bindings for the EGL API, which is used for managing OpenGL contexts and surfaces, particularly on embedded systems and mobile devices. ```go # Project: github.com/xlab/android-go/egl # Manifest: egl.yml # Description: Go bindings for EGL API. # Link: https://github.com/xlab/android-go # Note: The actual content of egl.yml is not provided, but it defines the Go bindings for EGL. ``` -------------------------------- ### Go cgo Aliases for C Constants Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Illustrates creating Go aliases for C constants using cgo. This method requires CGo and headers to be present for compilation, effectively linking to original C definitions. ```go // Result enumeration from https://www.khronos.org/registry/vulkan/specs/1.0/man/html/VkResult.html const ( Success Result = C.VK_SUCCESS NotReady Result = C.VK_NOT_READY Timeout Result = C.VK_TIMEOUT ) ``` -------------------------------- ### Vulkan Graphics API in Go Source: https://github.com/xlab/c-for-go/wiki/Top-5-reasons-to-use-bindings Highlights the successful transcription of a large C codebase (approx. 4000 lines) for the Vulkan Graphics API into Go. This demonstrates the feasibility of porting complex C libraries to Go, enabling developers to work with the same APIs and documentation but with Go's advantages. ```go // This is a conceptual Go code snippet representing the use of Vulkan bindings. // It shows how Go code might interact with the Vulkan API after transcription. package main import ( "fmt" "log" "unsafe" // Assuming a Go binding library for Vulkan exists, e.g., "github.com/vulkan-go/vulkan" vk "github.com/vulkan-go/vulkan" ) func main() { // Initialize Vulkan instance instanceExtensions := []string{ // vk.VK_KHR_surface, // vk.VK_KHR_win32_surface, // Example for Windows } instanceCreateInfo := &vk.InstanceCreateInfo{ SType: vk.StructureTypeInstanceCreateInfo, EnabledExtensionCount: uint32(len(instanceExtensions)), PEnabledExtensionNames: getStringPointers(instanceExtensions), // Other instance creation parameters... } var instance vk.Instance err := vk.CreateInstance(instanceCreateInfo, nil, &instance) if err != nil { log.Fatalf("Failed to create Vulkan instance: %v", err) } fmt.Println("Vulkan instance created successfully.") // --- Example of using a Vulkan function --- // Get available physical devices var physicalDeviceCount uint32 err = vk.EnumeratePhysicalDevices(instance, &physicalDeviceCount, nil) if err != nil { log.Fatalf("Failed to enumerate physical devices: %v", err) } physicalDevices := make([]vk.PhysicalDevice, physicalDeviceCount) err = vk.EnumeratePhysicalDevices(instance, &physicalDeviceCount, physicalDevices) if err != nil { log.Fatalf("Failed to enumerate physical devices: %v", err) } fmt.Printf("Found %d physical Vulkan devices.\n", physicalDeviceCount) // Select a physical device (e.g., the first one) if physicalDeviceCount > 0 { physicalDevice := physicalDevices[0] var pdProperties vk.PhysicalDeviceProperties vk.GetPhysicalDeviceProperties(physicalDevice, &pdProperties) fmt.Printf("Using physical device: %s\n", vk.ToString(&pdProperties.DeviceName[0])) } // Clean up Vulkan instance vk.DestroyInstance(instance, nil) fmt.Println("Vulkan instance destroyed.") } // Helper function to convert Go strings to C-style char* pointers func getStringPointers(strs []string) []*C.char { ptrs := make([]*C.char, len(strs)) for i, s := range strs { ptrs[i] = C.CString(s) } return ptrs } // Note: In a real scenario, you would need to manage the memory allocated by C.CString // using C.free() when the pointers are no longer needed. // This example omits that for brevity but it's crucial for production code. ``` -------------------------------- ### Comprehensive Real-World Rule Configuration Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section A detailed YAML configuration demonstrating various rule types (accept, ignore, replace, transform, load) applied across different scopes (global, function, type, const, private, post-global) for C-to-Go code generation. ```yaml Rules: global: - {action: accept, from: ^A} - {action: ignore, from: ^ABS} - {action: accept, from: ^android_Log} - {action: replace, from: ^android_Log, to: Log} - {action: replace, from: "(?i)^Android"} - {action: replace, from: ^A} function: - {action: accept, from: ^__android_log_write} - {action: replace, from: ^__android} - {action: ignore, from: JNI_OnLoad} - {action: ignore, from: JNI_OnUnload} - {action: ignore, from: ANativeActivity_onCreate} - {action: ignore, from: ASensorManager_getSensorList} type: - {action: accept, from: ^J} - {action: accept, from: jobject$} - {action: replace, from: "_t$"} const: - {action: ignore, from: TTS_H$} - {transform: lower} private: - {transform: unexport} post-global: - {transform: export} - {load: snakecase} ``` -------------------------------- ### Go Bindings for Android NDK Source: https://github.com/xlab/c-for-go/wiki/Examples The android-go project provides a platform for writing native Android apps in Go. It offers Go bindings for the Android NDK, enabling developers to access native Android APIs. ```go # Project: github.com/xlab/android-go # Manifest: android.yml # Description: Go bindings for the Android NDK. # Link: https://github.com/xlab/android-go # Note: The actual content of android.yml is not provided, but it defines the Go bindings for Android NDK. ``` -------------------------------- ### API Documentation: Built-in Transform Presets Source: https://github.com/xlab/c-for-go/wiki/Translator-config-section Lists and describes the functionality of built-in transformation presets available for use in c-for-go configurations. These presets simplify common naming conventions and documentation linking. ```APIDOC Built-in Presets: - snakecase: Description: Converts names to snake_case by replacing underscores and capitalizing subsequent letters. Configuration Example: RuleSpec{Action: ActionReplace, From: "_([^_]+)", To: "$1", Transform: TransformTitle} - doc.file: Description: Sets the documentation source to the file and line number where the entity is declared. Configuration Example: RuleSpec{Action: ActionDocument, To: "$path:$line"} - doc.google: Description: Creates a Google search URL for documentation using the file and entity name. Configuration Example: RuleSpec{Action: ActionDocument, To: "https://google.com/search?q=$file+$name"} ``` -------------------------------- ### Go Bindings for OpenGL ES v1 API Source: https://github.com/xlab/c-for-go/wiki/Examples Package gles provides Go bindings for the OpenGL ES v1 API, a subset of OpenGL designed for embedded systems like mobile phones. It enables 2D and 3D graphics rendering. ```go # Project: github.com/xlab/android-go/gles # Manifest: gles.yml # Description: Go bindings for OpenGL ES v1 API. # Link: https://github.com/xlab/android-go # Note: The actual content of gles.yml is not provided, but it defines the Go bindings for OpenGL ES v1. ```