C和围棋涉及C.free互操作性问题() [英] C and Go interoperability issue involving C.free()

查看:416
本文介绍了C和围棋涉及C.free互操作性问题()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个围棋函数封装了 proc_name中(PID,...)从函数 lib_proc.h

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

这是一个完整的 C原型


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

这可以在这里找到<$c$c>/Applications/X$c$c.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/libproc.h (至少在我的系统)。

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).

它遵循转到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;
    }

这code将无法编译,除非调用 C.free(unsafe.Pointer(...))进口不安全条款被删除。
DarwinProcess :: NameOf(PID)法的目的是只对工作的Mac OS X 它的实际工作的如 C.free(...)从code删除。

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.

在实际的形式后去建立我收到以下错误信息:
无法确定类的名字为C.free (仅此而已,这是整个编译器的输出)。

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).

删除 C.free(...)是不能接受的,我必须找到如何正确地释放与ç分配的内存。 CString的()

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.

推荐答案

libproc.h 不包括文件stdlib.h ,其中免费()声明。因此,编译器无法解析名称。我加了后的#include&LT;文件stdlib.h方式&gt; 在CGO注释的开始阻止我的系统上成功构建了code

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.

这篇关于C和围棋涉及C.free互操作性问题()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆