Skip to content

Instantly share code, notes, and snippets.

@sseemayer
Created October 31, 2013 09:02
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 sseemayer/7246463 to your computer and use it in GitHub Desktop.
Save sseemayer/7246463 to your computer and use it in GitHub Desktop.
CC = gcc
CFLAGS = -g -Wall -fPIC -std=gnu99 -O3 -march=native
all: libtest.so
libtest.so: test.o
$(CC) -shared -Wl,-soname,libtest.so -o libtest.so $<
%.o: %.c
$(CC) -c $(CFLAGS) $<
clean:
rm -vf libtest.so test.o
#include "test.h"
void callback_test(double* x, int n, callback_t callback) {
for(int i = 1; i <= 5; i++) {
for(int j = 0; j < n; j++) {
x[j] = x[j] / i;
}
callback(x, n);
}
}
typedef void (*callback_t)(
double *x,
int n
);
void callback_test(double* x, int n, callback_t callback);
#!/usr/bin/env python
import numpy as np
import numpy.ctypeslib as npct
import ctypes
import os.path
array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS')
callback_func = ctypes.CFUNCTYPE(
None, # return
ctypes.POINTER(ctypes.c_double), # x
ctypes.c_int # n
)
libtest = npct.load_library('libtest', os.path.dirname(__file__))
libtest.callback_test.restype = None
libtest.callback_test.argtypes = [array_1d_double, ctypes.c_int, callback_func]
@callback_func
def callback(x, n):
print("x: {0}, n: {1}".format(x[:n], n))
if __name__ == '__main__':
x = np.array([20, 13, 8, 100, 1, 3], dtype=np.double)
libtest.callback_test(x, x.shape[0], callback)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment