elixir 调用erlang 代码
备注:
项目比较简单,主要是elixir 混合erlang 代码,elixir 调用erlang 模块方法
1. 初始化项目
mix new erlangelixirdemo
项目结构如下:
├── README.md
├── config
│ └── config.exs
├── lib
│ └── erlangelixirdemo.ex
├── mix.exs
└── test
├── erlangelixirdemo_test.exs
└── test_helper.exs
2. 添加erlang 支持
创建src 目录,并编写erlang code
项目结果如下:
├── README.md
├── config
│ └── config.exs
├── lib
│ └── erlangelixirdemo.ex
├── mix.exs
├── src
│ └── app.erl
└── test
├── erlangelixirdemo_test.exs
└── test_helper.exs
src/app.erl 代码如下:
-module(app).
%%API
-export([
login/0,
userlogin/0,
login/2,
userlogin/1
]).
-record(user, { name, age }).
login() ->
{ok,'dalongdemo'}.
login(Name , Password) ->
{ok,'appdemo'}.
userlogin()->
#user{name='dalongdemo',age=44}.
userlogin(User)->
User.
3. elixir 调用erlang 模块方法
lib/erlangelixirdemo.ex 代码如下:
defmodule Erlangelixirdemo do
@moduledoc """
Documentation for Erlangelixirdemo.
"""
def call_erlang do
IO.inspect :app.userlogin()
end
end
4. 编译访问
iex -S mix
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
Compiling 1 file (.erl)
Compiling 1 file (.ex)
Generated erlangelixirdemo app
Interactive Elixir (1.6.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> E
Elixir Enum Enumerable
ErlangError Erlangelixirdemo Exception
iex(1)> Erlang
ErlangError Erlangelixirdemo
iex(1)> Erlangelixirdemo.
MixProject call_erlang/0
iex(1)> Erlangelixirdemo.call_erlang
{:user, :dalongdemo, 44}
{:user, :dalongdemo, 44}
5. 说明
默认mix compile 的时候,对于erlang 代码是在src 目录进行编译的,同时可以在 mix.exs 修改
def project do
[
app: :appdemo,
version: "0.1.0",
elixir: "~> 1.6",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
如下:
def project do
[app: :my_app,
version: "0.0.1",
elixir: "~> 1.0",
erlc_paths: ["src"], # ADD THIS OPTION
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps]
end
6. 参考代码
https://github.com/rongfengliang/elixir-erlang