What interfaces exist to tie Erlang with C++?
问题:
回答1:
Native implemented functions: available in the latest Erlang/OTP version, allows you to implement any of your functions in C.
Port drivers: you can link a C code to the Erlang VM, and access it using port_command.
C Nodes: With the ei library you can mimic a VM and talk to your Erlang VMs using the Erlang distribution format.
回答2:
The closest thing I know for interfacing Erlang with C++ directly is EPAPI. Of course it relies on the tried and tested C erl_interface
that comes standard with the Erlang distribution.
回答3:
To Zed's excellent answer, I would add open_port()
. It lets you start an external program and communicate with it from Erlang using its standard in and out. You can use it like Unix pipes by giving the {line, L} option, or there's also the length-prefixed {packet, N} option which I find to be safer and more efficient.
The advantage of this over NIFs and port drivers is that your Erlang code is totally insulated from the C code. The C program can smash its own stack, double-free blocks of memory, enter an infinite loop, whatever. None of this stops your Erlang code. At worst, you close the Erlang port and re-open it if things go pear-shaped.
回答4:
Anyone interested in the erlang/C++ integration aspect, may also want to check out this article: Rewriting Playdar: C++ to Erlang, massive savings:
I’ve heard many anecdotes and claims about how many lines of code are saved when you write in Erlang instead of [C++/other language]. I’m happy to report that I now have first-hand experience and some data to share.
I initially wrote Playdar in C++ (using Boost and Asio libraries), starting back in February this year. I was fortunate to be working with some experienced developers who helped me come to terms with C++. There were three of us hacking on it regularly up until a few months ago, and despite being relatively new to C++, I’ll say that we ended up with a well designed and robust codebase, all things considered.