Erlang Tutorial
Erlang Useful Resources
Selected Reading
- Erlang - Web Programming
- Erlang - Drivers
- Erlang - Performance
- Erlang - Concurrency
- Erlang - OTP
- Erlang - Distributed Programming
- Erlang - Ports
- Erlang - Databases
- Erlang - Emails
- Erlang - Processes
- Erlang - Funs
- Erlang - Binaries
- Erlang - BIFS
- Erlang - Guards
- Erlang - Pattern Matching
- Erlang - Preprocessors
- Erlang - Header Files
- Erlang - Macros
- Erlang - Exceptions
- Erlang - Records
- Erlang - Tuples
- Erlang - Maps
- Erlang - Atoms
- Erlang - File I/O
- Erlang - Lists
- Erlang - Strings
- Erlang - Numbers
- Erlang - Recursion
- Erlang - Modules
- Erlang - Functions
- Erlang - Decision Making
- Erlang - Loops
- Erlang - Operators
- Erlang - Variables
- Erlang - Data Types
- Erlang - Shell
- Erlang - Basic Syntax
- Erlang - Environment
- Erlang - Overview
- Erlang - Home
Erlang Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Erlang - Drivers
Erlang - Drivers
Sometimes we want to run a foreign-language program inside the Erlang Runtime System. In this case, the program is written as a shared pbrary that is dynamically pnked into the Erlang runtime system. The pnked-in driver appears to the programmer as a port program and obeys exactly the same protocol as for a port program.
Creating a Driver
Creating a pnked-in driver is the most efficient way of interfacing foreign-language code with Erlang, but it is also the most dangerous. Any fatal error in the pnked-in driver will crash the Erlang System.
Following is an example of a driver implementation in Erlang −
Example
-module(helloworld). -export([start/0, stop/0]). -export([twice/1, sum/2]). start() -> start("example1_drv" ). start(SharedLib) -> case erl_ddll:load_driver("." , SharedLib) of ok -> ok; {error, already_loaded} -> ok; _ -> exit({error, could_not_load_driver}) end, spawn(fun() -> init(SharedLib) end). init(SharedLib) -> register(example1_pd, self()), Port = open_port({spawn, SharedLib}, []), loop(Port). stop() -> example1_pd ! stop. twice(X) -> call_port({twice, X}). sum(X,Y) -> call_port({sum, X, Y}). call_port(Msg) -> example1_pd ! {call, self(), Msg}, receive {example1_pd, Result} -> Result end. LINKED-IN DRIVERS 223 loop(Port) -> receive {call, Caller, Msg} -> Port ! {self(), {command, encode(Msg)}}, receive {Port, {data, Data}} -> Caller ! {example1_pd, decode(Data)} end, loop(Port); stop -> Port ! {self(), close}, receive {Port, closed} -> exit(normal) end; { EXIT , Port, Reason} -> io:format("~p ~n" , [Reason]), exit(port_terminated) end. encode({twice, X}) -> [1, X]; encode({sum, X, Y}) -> [2, X, Y]. decode([Int]) -> Int.
Please note that working with drivers is extremely complex and care should be taken when working with drivers.
Advertisements