go v1.17.3. vscode v1.62.2. Go extension is latest version as of now.
I'm working on a small CGo application, using vscode with the go extension.
I've managed to get my Cgo annotations (CFLAGS, et cetera) working with no errors. I'm now trying to make calls to the C package and the included libs. First, I'm just trying simple calls to the C package, along with a call to a simple function in the library I'm using that just returns the version of the library, as a string.
I'm using the following as my doc resources:
- https://pkg.go.dev/cmd/cgo
- https://karthikkaranth.me/blog/calling-c-code-from-go/
- https://riptutorial.com/go/example/22191/calling-c-function-from-go
The very first thing that worked was a simple call to that "version" function, and then I printed the value of that with a simple Println call. It prints a hex value, so I guess it did something.
Past that, I'm having problems.
From what I understand, the return value from that function should be a "C String", so I have to convert it to a "Go String".
Right in my first resource, it shows this:
// C string to Go string
func C.GoString(*C.char) string
So, I tried simply doing something like this:
voltageVersion := C.VeGetVersion()
fmt.Println(voltageVersion)
gostring := C.GoString(voltageVersion)
The first line is the call to the function in the library. The second line prints the hex value, and that worked. The third line is my attempt to get it into a form I can use. In vscode, it has an error on that line, saying "GoString not declared by package C".
I'm not sure what I'm missing here.
Update:
I figured out what it wanted. I'm pretty sure there's a bug here somewhere, but I'm not sure where.
This is my original code:
// #cgo CFLAGS: -g -Wall -I${SRCDIR}/../include
// #cgo LDFLAGS: -L${SRCDIR}/../lib/linux -lvibesimple -lcurl -lssl -lvibecrypto -lvibeictk -lvibeserver
// #include <stdio.h>
// #include <errno.h>
// #include "veapi.h"
import "C"
import (
"fmt"
)
func Encrypt(datatype string, data string) (result string) {
voltageVersion := C.VeGetVersion()
fmt.Println(voltageVersion)
version := C.GoString(voltageVersion)
This has vscode reporting that error on the last line.
Here is the changed version that doesn't have that symptom:
/*
#cgo CFLAGS: -g -Wall -I${SRCDIR}/../include
#cgo LDFLAGS: -L${SRCDIR}/../lib/linux -lvibesimple -lcurl -lssl -lvibecrypto -lvibeictk -lvibeserver
#include <stdio.h>
#include <errno.h>
#include "veapi.h"
*/
import "C"
import (
"fmt"
)
func Encrypt(datatype string, data string) (result string) {
voltageVersion := C.VeGetVersion()
fmt.Println(voltageVersion)
version := C.GoString(voltageVersion)
I only changed the comment format. The original version matches the style used in the Go documentation. The version that is now working isn't even suggested as an alternative, although it would be logical to assume that would also work. I would have never expected one form to work and the other not to.