Dynamic imports

772 views
Skip to first unread message

Rocky Bernstein

unread,
Mar 15, 2013, 10:46:02 PM3/15/13
to golan...@googlegroups.com
Here is the second question I asked IRC that I think deserve a slightly wider audience.

First to try to motivate where I am coming from.

Again, I've been writing go bindings for C library GNU Readline. But that is part of a larger effort (if I get that far), to possibly extend igo, write a debugger for an interpreted go, or possibly write a debugger largely written in go for go.

These all have command-line interfaces which need a readline program. The alternatives include liner, and GNU Readline. liner is pure go so it available everywhere . But GNU Readline is much more complete and it the de-facto standard. It is not unreasonable for users to have either one or both of these installed.

Given this, what one would like to do is create a generic "readline" package that loads either one based on availability and desirability.

I get the impression one can not have a conditional import, nor can one dynamically run import at run time. Yes there are build tags, but that happens at compile time; we want something that happens at run time.

The lack of dynamic import also seriously reduces the usability of igo. Here, inside of igo one would want to say for example "import fmt" and have that work.

Thoughts?

Carlos Castillo

unread,
Mar 16, 2013, 5:22:59 PM3/16/13
to golan...@googlegroups.com
It is possible to sort of have a dynamic import if you use cgo to access libdl for the dlopen/dlsym function calls. Then you need to use FFI, or some such library to make calls to those C-function pointers that dlsym provides you. This will allow you to at runtime attempt to access a shared library, and gracefully degrade if the access fails. A while ago I build an incomplete package to do so https://github.com/cookieo9/goffi, I haven't updated it in a while...

Some problems you'll run into include that you don't have access to headers or macros, so some libraries that use macros as part of their functionality will not work, and you will have to "hard code" constants into your source which can cause portability issues down the road. Also, I've never tested it on windows, but I assume it won't work anyway, as neither libdl, nor readline are available natively there.

Also it will be slower as there will be a large overhead on each call, not that big a deal for readline though...
Reply all
Reply to author
Forward
0 new messages