Skip to content

Commit 80c3cc4

Browse files
committed
Defer loading the NIF until opening a SPI bus
This change moves the NIF load from the time at which the module is loaded to the time when SPI actually is used. The primary motivation for doing this is to defer native code crashes from happening at load time to the time of first use. Load time is harder to debug and sometimes its not clear which NIF caused the crash. The calls to `apply` get around some complexity with ignoring Dialyzer warnings. Dialyzer can't figure out that the recursive looking call actually invokes the NIF code.
1 parent 0763e0d commit 80c3cc4

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

lib/spi/spi_nif.ex

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,17 @@
33
# SPDX-License-Identifier: Apache-2.0
44

55
defmodule Circuits.SPI.Nif do
6-
@on_load {:load_nif, 0}
7-
@compile {:autoload, false}
8-
96
@moduledoc false
107

11-
def load_nif() do
8+
defp load_nif() do
129
nif_binary = Application.app_dir(:circuits_spi, "priv/spi_nif")
1310
:erlang.load_nif(to_charlist(nif_binary), 0)
1411
end
1512

16-
def open(_bus_name, _mode, _bits_per_word, _speed_hz, _delay_us, _lsb_first) do
17-
:erlang.nif_error(:nif_not_loaded)
13+
def open(bus_name, mode, bits_per_word, speed_hz, delay_us, lsb_first) do
14+
with :ok <- load_nif() do
15+
apply(__MODULE__, :open, [bus_name, mode, bits_per_word, speed_hz, delay_us, lsb_first])
16+
end
1817
end
1918

2019
def config(_ref) do
@@ -30,7 +29,8 @@ defmodule Circuits.SPI.Nif do
3029
end
3130

3231
def info() do
33-
:erlang.nif_error(:nif_not_loaded)
32+
:ok = load_nif()
33+
apply(__MODULE__, :info, [])
3434
end
3535

3636
def max_transfer_size() do

0 commit comments

Comments
 (0)