Created
May 23, 2019 17:32
-
-
Save jpata/e23c754e85d45982445456b78d1ce0a3 to your computer and use it in GitHub Desktop.
numba CFFI class method C wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//compile with g++ -fPIC mylib.cc -shared -o mylib.dylib | |
class MyClass { | |
public: | |
MyClass(const char* filename) { | |
//do something with filename | |
} | |
double func(int a) { | |
//an expensive C++ function | |
return 0.0; | |
} | |
}; | |
extern "C" { | |
void* new_class(const char* filename) { | |
return new MyClass(filename); | |
} | |
double class_func(void* cls, int a) { | |
return ((MyClass*)cls)->func(a); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numba | |
from cffi import FFI | |
ffi = FFI() | |
ffi.cdef(""" | |
void* new_class(const char* filename); | |
double class_func(void* cls, int a); | |
""") | |
mylib = ffi.dlopen("mylib.dylib") | |
class_func = mylib.class_func | |
c = mylib.new_class("asd") | |
@numba.njit | |
def call_myfunc(a): | |
x = class_func(c, a) | |
#throws exception as the type of c ('_cffi_backend.CData') is not known to Numba | |
call_myfunc(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment