强制定义Go结构体以将unsafe.Pointer()转换为C结构体

4
与 C 代码互操作时,我无法直接转换一个结构体,因此被迫在 Go 中定义一个等效的结构体。 来自 libproc.h 的 C 函数为:
int proc_pidinfo(int pid, int flavor, uint64_t arg,  void *buffer, int buffersize)

flavor==PROC_PIDTASKINFO的C结构体为proc_taskinfo,定义在sys/proc_info.h中(由libproc.h包含):

struct proc_taskinfo {
    uint64_t        pti_virtual_size;   /* virtual memory size (bytes) */
    uint64_t        pti_resident_size;  /* resident memory size (bytes) */
    uint64_t        pti_total_user;     /* total time */
    uint64_t        pti_total_system;
    uint64_t        pti_threads_user;   /* existing threads only */
    uint64_t        pti_threads_system;
    int32_t         pti_policy;     /* default policy for new threads */
    int32_t         pti_faults;     /* number of page faults */
    int32_t         pti_pageins;        /* number of actual pageins */
    int32_t         pti_cow_faults;     /* number of copy-on-write faults */
    int32_t         pti_messages_sent;  /* number of messages sent */
    int32_t         pti_messages_received;  /* number of messages received */
    int32_t         pti_syscalls_mach;  /* number of mach system calls */
    int32_t         pti_syscalls_unix;  /* number of unix system calls */
    int32_t         pti_csw;            /* number of context switches */
    int32_t         pti_threadnum;      /* number of threads in the task */
    int32_t         pti_numrunning;     /* number of running threads */
    int32_t         pti_priority;       /* task priority*/
};

即使Go代码实际上可以工作,我仍然无法直接使用C.proc_taskinfo。 Go函数是propertiesOf():完整源代码在这里
如果我引用C结构,我会得到一个类似于我在最新问题中报告的错误:could not determine kind of name for C.proc_taskinfo,但这次我确信定义已经被导入了#include
1个回答

7
根据文档,要直接访问结构体、联合体或枚举类型,请在其前面加上struct_、union_或enum_,例如C.struct_stat。使用C.struct_proc_taskinfo。

+1 这个回答解决了我的问题,让我更好地理解了 C/Go 之间的互操作性。我认为这应该在文档中有提到(我会查阅),但像这样重要的事情应该更清晰地呈现出来(用很多粗体句子……)。 - gsscoder
已应用更改(已构建并通过测试),如果有任何人对完整的(学习)项目源代码感兴趣,可以通过此链接进行查看:https://goo.gl/he4bPH。 - gsscoder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接