Embedding OCaml within Python
Peter Strempel
peterstrempel at yahoo.com
Wed Apr 28 04:43:20 EDT 2004
Max Powers wrote:
> I've spent an interesting day searching the web for help with calling
> OCaml functions from a python program and have come to the newsgroup
> for some advice
I stumbled over a similar task few months ago. I found no direct way to call
OCaml functions from Python directly (maybe there is and I didn't find it),
but I solved it by calling the OCaml code from C which itself is an
extension loaded by Python.
Python -> C extension -> OCaml -> callback to C -> callback to Python
This is sort of ugly, but works. Actually Python is supposed to be the glue
language, not C. :)
The passed values are simple types, not classes or arrays, so this isn't
overly complex, but can probably get if you need to pass non-trivial values
because C needs to translate between OCaml and Python types then.
I implemented the above without SWIG or similar tools, simply because I
prefer to write the boilerplate code at least once to understand how it
works. Plans are to use SWIG later.
I approached the task by writing some C program which calls the OCaml stuff
and implements required callbacks first. Then later adding the interface to
Python. It actually isn't that complex if you try to treat the Python <-> C
and the C <-> OCaml parts individually. Both Python and OCaml have excellent
documentation covering interfacing with C.
In reply to your last remark, I think you are not in a world of pain. But
it's probably not the most trivial thing to do either.
I would appreciate pointers how to do this in a more elegant way, though.
I am in no way an OCaml expert, so chances are high I missed something here.
Peter
More information about the Python-list
mailing list