Skip to content

Instantly share code, notes, and snippets.

@jpata
Created May 23, 2019 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpata/e23c754e85d45982445456b78d1ce0a3 to your computer and use it in GitHub Desktop.
Save jpata/e23c754e85d45982445456b78d1ce0a3 to your computer and use it in GitHub Desktop.
numba CFFI class method C wrapper
//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);
}
}
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