go

could not determine kind of name for C.free


I am trying to use C.free in my Golang application. My code is as follows:

package main

import (
    "fmt"
    "unsafe"
)

// #include <stdlib.h>

import (
    "C"
)


//export FreeMemory
func FreeMemory(pointer *int64) {
    C.free(unsafe.Pointer(pointer))
}

I have done some searching and I understand the error was because I don't have stdlib.h included, but I do.

This is my build command: go build --buildmode=c-shared -o main.dll. The error I get after building is: could not determine kind of name for C.free

My OS is Windows 10

Thanks


Solution

  • If the import of "C" is immediately preceded by a comment, that comment, called the preamble, is used as a header when compiling the C parts of the package. For example:

    // #include <stdio.h> 
    // #include <errno.h> 
    import "C"
    

    Using immediately preceding Go line comments:

    package main
    
    import "unsafe"
    
    // #include <stdlib.h>
    import "C"
    
    //export FreeMemory
    func FreeMemory(pointer *int64) {
        C.free(unsafe.Pointer(pointer))
    }
    
    func main() {}
    

    Using immediately preceding Go general comments:

    package main
    
    import "unsafe"
    
    /*
    #include <stdlib.h>
    */
    import "C"
    
    //export FreeMemory
    func FreeMemory(pointer *int64) {
        C.free(unsafe.Pointer(pointer))
    }
    
    func main() {}