Calling C function pointers from Go

881 views
Skip to first unread message

J. Bates

unread,
Oct 21, 2011, 11:25:34 AM10/21/11
to golang-nuts
Is there a way to call C function pointers from Go? I've tried doing
it the obvious way (by just treating the variable as a function) but I
receive "cannot call non-function" at build time.

To get around it, I can just create a C function which takes the
function pointer and arguments as arguments, but I'm wondering if
there's a better way. I don't know much about the inner-working of
cgo, but if it's not implemented I imagine it's technically possible.

Jan Mercl

unread,
Oct 21, 2011, 12:31:06 PM10/21/11
to golan...@googlegroups.com
Go and C calling convention are not compatible, at least in 6g and friends. I think CGO generates the "bridge" when calling a C function, so it might in theory create the same for a C function pointer, though I don't know if that's suported. The "can't call non function" error looks like a improper type definition/conversion on Go side, regardless of it can or cannot work. The later seems more probable to me. Invoking the C function pointer via a manually writen C stub is the way to go, I guess.

J. Bates

unread,
Oct 21, 2011, 12:53:39 PM10/21/11
to golang-nuts
Yeah, I poked around cgo and the code it generates. The bridges could
theoretically work with function pointers, but it's not implemented at
all as far as I can tell. It looks like cgo just converts all function
pointers to void* in these "bridges". If this isn't discluded for some
philosophical reason, then I'm tempted to implement it myself.

Then again, if the compiler actually decides to inline my stubs, the
end-result isn't much (any?) different.

Russ Cox

unread,
Oct 21, 2011, 1:23:07 PM10/21/11
to J. Bates, golang-nuts
On Fri, Oct 21, 2011 at 11:25, J. Bates <dost...@gmail.com> wrote:
> Is there a way to call C function pointers from Go? I've tried doing
> it the obvious way (by just treating the variable as a function) but I
> receive "cannot call non-function" at build time.

Right, the answer is no, because each call needs a direct target
to hit, so that it can call the right stub.

> To get around it, I can just create a C function which takes the
> function pointer and arguments as arguments, but I'm wondering if
> there's a better way.

That sounds like an excellent way.

Russ

Reply all
Reply to author
Forward
0 new messages