Cgo: wrapping varargs

540 views
Skip to first unread message

Jsor

unread,
Jun 4, 2015, 5:25:50 PM6/4/15
to golan...@googlegroups.com
I know that cgo doesn't do varargs, but I came across a stack overflow question suggesting to wrap it, however, as far as I can tell, there's no way to pass an array as varargs either. Does anyone know a workaround?

I can't refactor to eliminate varargs, I'm trying to fix go-python:


The Python API heavily relies on varargs, right now the only workaround is really tedious tuple fiddling if you want to do complicated things like "calling a function."

Ian Lance Taylor

unread,
Jun 4, 2015, 5:38:07 PM6/4/15
to Jsor, golang-nuts
On Thu, Jun 4, 2015 at 1:47 PM, Jsor <jrago...@gmail.com> wrote:
>
> I know that cgo doesn't do varargs, but I came across a stack overflow
> question suggesting to wrap it, however, as far as I can tell, there's no
> way to pass an array as varargs either. Does anyone know a workaround?

cgo works by generating C code to call the C function. The nature of
C varargs is that the arguments must actually be written out in the
calling C code. C has no equivalent to Go's F(args...). So this is
insoluble in principle. There is no way to generate C code to call a
C function with an unknown number of arguments.

That said, if there is some reasonable limit on the number of
arguments, you can force the Go side to extra unused arguments to each
call. That is basically what the syscall package does, with Syscall3,
Syscall6, and Syscall9.

Ian

Julian Phillips

unread,
Jun 4, 2015, 11:16:37 PM6/4/15
to Jsor, golan...@googlegroups.com
This is what I did for my Python bindings (in this case, wrapping
PyArg_ParseTuple):

https://github.com/qur/gopy/blob/master/lib/utils.c#L25

called from here:

https://github.com/qur/gopy/blob/master/lib/arg.go#L89

--
Julian

Sebastien Binet

unread,
Jun 5, 2015, 4:28:08 AM6/5/15
to Julian Phillips, Jsor, golang-nuts
ah! nice.
I could dust off my old ffi wrapper for this :)
https://github.com/gonuts/ffi

-s
Reply all
Reply to author
Forward
0 new messages