简体   繁体   中英

cgo wrote func in cgo header to print data, but nothing gets printed from it

I'm trying to write a small cgo application using vscode and vscode-go.

I'm at least three levels deep in problems. I needed to copy a Go string to an allocated C buffer and then pass that inside a struct to a function provided by a C library. That function is returning an error that doesn't give me enough information, so I'm trying to examine what I'm passing to the function. I'm not certain I'm doing the memory copy properly, so I wanted to write a C function in the cgo header that I can call to just print out a number of hex bytes from an address. The problem I'm having right now is that that method isn't printing ANYTHING, even a simple printf statement.

My cgo header looks like this:

/*
#cgo CFLAGS: -g -Wall -I${SRCDIR}/../include
#cgo LDFLAGS: -L${SRCDIR}/../lib/linux ...
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "..."

typedef struct {
    int size;
    void *data;
} info;

void printBytes(info *data) {
    printf("In printBytes.");
}

*/

In one of the functions in the same module, I have this code:

plaintextBuffer := C.malloc(C.ulong(C.sizeof_char * len(data)))

buf := (*[1 << 30]byte)(plaintextBuffer)
copy(buf[:], data)

fmt.Println("About to call printBytes.")
info := &C.info{size: C.int(len(data)), data: plaintextBuffer}
C.printBytes(info)

I am not certain at all whether those two lines for copying the string to the buffer are correct, but they compile and don't panic when they run, so they couldn't be that bad. :)

In any case, I wanted to verify whether it actually did work properly, by calling that "printBytes" function (which obviously needs more code to do something useful). For the first test, I just want to see "In printBytes." when I run it. However, what I see when I run it is nothing. I see the "About to call..." line, and then a print statement that comes after this code.

I also tried changing "printBytes" and "info" to "PrintBytes" and "Info"(just the type) in the def and the reference, and it had no effect on the result.

I could use advice on any of this, starting with why the function doesn't print anything, or advice on whether that copy code is correct, or anything else.

go 1.7

plaintextBuffer := C.malloc(C.ulong(C.sizeof_char * len(data)))
C.free(unsafe.Pointer(plaintextBuffer))
slice := unsafe.Slice((*byte)(plaintextBuffer), len(data))
copy(slice[:], data)
fmt.Print(slice)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM