Using Go's Syscall and passing a "struct" by reference

260 views
Skip to first unread message

Carlos Torres

unread,
Aug 1, 2014, 6:59:18 PM8/1/14
to golan...@googlegroups.com
Hi all,

I'm trying to understand Go's syscall.Syscall functions. 

So, in C, I can do the following:

struct perf_event_attr pe_cycles;
int pe_cycles_fd;


memset
(&pe_cycles, 0, sizeof(struct perf_event_attr));
pe_cycles
.type = PERF_TYPE_HARDWARE;
pe_cycles
.size = sizeof(struct perf_event_attr);
pe_cycles
.config = PERF_COUNT_HW_CPU_CYCLES;

..... // trivial struct setup


pe_cycles_fd
= syscall(__NR_perf_event_open, 0, -1, -1, 0);
if (pe_cycles_fd == 1) {
  fprintf
(stderr, "Error", pe_cycles_fd.config);
}

// pe_cycles is populated


I want to achieve the same in Go, but I can't find documentation on how to pass in a struct by reference to 
syscall.Syscall6(syscall.SYS_PERF_EVENT_OPEN, ?, 0, -1, -1, 0, 0)


Any help pointing to an example, or documentation would be greatly appreciated.

Thanks

Ian Lance Taylor

unread,
Aug 1, 2014, 7:37:34 PM8/1/14
to Carlos Torres, golang-nuts
On Fri, Aug 1, 2014 at 3:59 PM, Carlos Torres
<ctorresk8...@gmail.com> wrote:
>
> I'm trying to understand Go's syscall.Syscall functions.
>
> So, in C, I can do the following:
>
> struct perf_event_attr pe_cycles;
> int pe_cycles_fd;
>
>
> memset(&pe_cycles, 0, sizeof(struct perf_event_attr));
> pe_cycles.type = PERF_TYPE_HARDWARE;
> pe_cycles.size = sizeof(struct perf_event_attr);
> pe_cycles.config = PERF_COUNT_HW_CPU_CYCLES;
>
> ..... // trivial struct setup
>
>
> pe_cycles_fd = syscall(__NR_perf_event_open, 0, -1, -1, 0);
> if (pe_cycles_fd == 1) {
> fprintf(stderr, "Error", pe_cycles_fd.config);
> }
>
> // pe_cycles is populated
>
>
> I want to achieve the same in Go, but I can't find documentation on how to
> pass in a struct by reference to
> syscall.Syscall6(syscall.SYS_PERF_EVENT_OPEN, ?, 0, -1, -1, 0, 0)

First, consider using cgo to just call the C function instead if there
is one. That should be straightforward.

If that doesn't work, then you'll need to define the struct in Go.
Then you can write
syscall.Syscall6(syscall.SYS_PERF_EVENT_OPEN,
uintptr(unsafe.Pointer(&mystruct)), 0, -1, -1, 0, 0)

There are many examples in the syscall package.

Ian
Reply all
Reply to author
Forward
0 new messages