Thanks to visit codestin.com
Credit goes to docs.rs

arrayfire/core/
backend.rs

1use super::defines::{AfError, Backend};
2use super::error::HANDLE_ERROR;
3
4use libc::{c_int, c_uint};
5
6extern "C" {
7    fn af_set_backend(bknd: u8) -> c_int;
8    fn af_get_backend_count(num_backends: *mut c_uint) -> c_int;
9    fn af_get_available_backends(backends: *mut c_int) -> c_int;
10    fn af_get_active_backend(backend: *mut c_int) -> c_int;
11}
12
13/// Toggle backends between cuda, opencl or cpu
14///
15/// # Parameters
16///
17/// - `backend` to which to switch to
18pub fn set_backend(backend: Backend) {
19    unsafe {
20        let err_val = af_set_backend(backend as u8);
21        HANDLE_ERROR(AfError::from(err_val));
22    }
23}
24
25/// Get the available backend count
26pub fn get_backend_count() -> u32 {
27    unsafe {
28        let mut temp: u32 = 0;
29        let err_val = af_get_backend_count(&mut temp as *mut c_uint);
30        HANDLE_ERROR(AfError::from(err_val));
31        temp
32    }
33}
34
35/// Get the available backends
36pub fn get_available_backends() -> Vec<Backend> {
37    unsafe {
38        let mut temp: i32 = 0;
39        let err_val = af_get_available_backends(&mut temp as *mut c_int);
40        HANDLE_ERROR(AfError::from(err_val));
41
42        let mut b = Vec::new();
43        if temp & 0b0100 == 0b0100 {
44            b.push(Backend::OPENCL);
45        }
46        if temp & 0b0010 == 0b0010 {
47            b.push(Backend::CUDA);
48        }
49        if temp & 0b0001 == 0b0001 {
50            b.push(Backend::CPU);
51        }
52
53        b
54    }
55}
56
57/// Get current active backend
58pub fn get_active_backend() -> Backend {
59    unsafe {
60        let mut temp: i32 = 0;
61        let err_val = af_get_active_backend(&mut temp as *mut c_int);
62        HANDLE_ERROR(AfError::from(err_val));
63        match (err_val, temp) {
64            (0, 0) => Backend::DEFAULT,
65            (0, 1) => Backend::CPU,
66            (0, 2) => Backend::CUDA,
67            (0, 4) => Backend::OPENCL,
68            _ => panic!("Invalid backend retrieved, undefined behavior."),
69        }
70    }
71}