Unable to return char* from a c function (CGO)

I am unable to return the char pointer from the getrpath() function. I know that the C function is being called in the below code because a printf can print the realpath. I can’t seem to get the char* back into the main() function though.

Any advice? Thank you.

package main

/*
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

char* getrpath(char *symlink) {
    char *actualpath = malloc(PATH_MAX);
    return realpath(symlink, actualpath)
}

*/
import "C"
import (
    "fmt"
    "os"
    "path"
    "unsafe"
)

func getArgv() string {
    return fmt.Sprintf("./%s", path.Base(os.Args[0]))
}

func main() {
    slink := C.CString(getArgv())
    defer C.free(unsafe.Pointer(slink))
    ret := C.getrpath(slink)
    fmt.Println(C.GoString(ret))
}

What do you mean by “unable?” Are you getting an error?

Nope… no error at all. It compiles just fine but prints nothing in the main() function… just a blank line. Any ideas? I must have spent hours looking at different ways to get the pointer back into main… Stack Overflow and the Golang Google Groups… I actually made a few different versions but all have the same result.

Okay ended up getting it but only by calling the realpath function directly:

package main

/*
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
*/
import "C"
import (
    "bytes"
    "fmt"
    "unsafe"
)

func currentDir() []byte {
    return []byte{0x2e, 0x2f}
}

func rpath() string {
    relativePath := currentDir()
    limit := make([]byte, C.PATH_MAX)
    slink := make([]byte, len(relativePath)+1)
    copy(slink, relativePath)
    C.realpath(
        (*C.char)(unsafe.Pointer(&slink[0])),
        (*C.char)(unsafe.Pointer(&limit[0])))
    return C.GoString((*C.char)(unsafe.Pointer(&limit[0])))
    }

func main() {
    fmt.Println(rpath())
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.