duanlvxing7707 2015-05-27 11:34
浏览 184
已采纳

涉及C.free()的C and Go互操作性问题

I've a Go function that wraps the proc_name(pid,...) function from lib_proc.h.

This is the complete C prototype:


int proc_name(int pid, void * buffer, uint32_t buffersize) __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);

that can be found here /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/libproc.h (at least on my system).

It follows Go code:


package goproc

    /*
    #include "libproc.h"

    int call_proc_name(int pid, char *name, int name_size) {
      return proc_name(pid, name, name_size);
    }
    */
    import "C"
    import "unsafe"
    import "strings"

    type DarwinProcess struct {
        Process
    }

    func (DarwinProcess) NameOf(pid int) string {
        name := C.CString(strings.Repeat("\x00", 1024))
        defer C.free(unsafe.Pointer(name))
        nameLen := C.call_proc_name(C.int(pid), name, C.int(1024))
        var result string

        if (nameLen > 0) {
            result = C.GoString(name);
        } else {
            result = ""
        }

        return result;
    }

This code won't compile unless the call to C.free(unsafe.Pointer(...)) and import "unsafe" clause are removed. DarwinProcess::NameOf(pid) method is meant to work only on Mac OS X and it actually works if C.free(...) is removed from code.

In its actual form after go build I get the following error message: could not determine kind of name for C.free (and nothing more, this is the whole compiler output).

Removing C.free(...) is not acceptable to me, I must find how to properly free the memory allocated with C.CString().

I'm puzzled since, according to documentation, everything is done properly. I have not been able to find a solution nor searching here nor on the web.

  • 写回答

1条回答 默认 最新

  • dsa89029 2015-05-27 11:54
    关注

    libproc.h doesn't include stdlib.h, where free() is declared. As such, the compiler cannot resolve the name. After I added #include <stdlib.h> at the beginning of the cgo comment block your code built successfully on my system.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败