Skip to content

Instantly share code, notes, and snippets.

Created December 24, 2013 00:22
Show Gist options
  • Save anonymous/8106984 to your computer and use it in GitHub Desktop.
Save anonymous/8106984 to your computer and use it in GitHub Desktop.
some sample code playing around with ctypes and cffi for calling external code written in C from within Python.
from cffi import FFI
ffi = FFI()
ffi.cdef('int classify(float x, float y, int num_class, float* class_x, float* class_y);')
libcls = ffi.dlopen('libclassify.A.dylib')
xmeans = ffi.new("float[2]", (5.0, 2.0))
ymeans = ffi.new("float[2]", (5.0, 2.0))
print '(3.0, 3.0): %d' % libcls.classify(3.0, 3.0, 2, xmeans, ymeans) # (3.0, 3.0): 1
print '(4.0, 4.0): %d' % libcls.classify(4.0, 4.0, 2, xmeans, ymeans) # (4.0, 4.0): 0
// compile into a binary (by default, a.out) with:
// clang classify.c
// or into a shared library for use by Python with:
// clang -dynamiclib -ansi classify.c -current_version 1.0 -compatibility_version 1.0 -o libclassify.A.dylib
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
int classify(float x, float y, int num_class, float* class_x, float* class_y) {
float* dists = malloc(num_class * sizeof(float));
if (dists == NULL)
exit(1);
for (int i=0; i<num_class; i++)
dists[i] = sqrt(pow(x - class_x[i], 2) + pow(y - class_y[i], 2));
int idxArgmin = 0;
for (int j=0; j<num_class; j++)
if (dists[j] < dists[idxArgmin])
idxArgmin = j;
free(dists);
return idxArgmin;
}
int main() {
float class_x[2] = {5.0f, 2.0f};
float class_y[2] = {5.0f, 2.0f};
printf("(3.0, 3.0): %d\n", classify(3.0, 3.0, 2, class_x, class_y)); // (3.0, 3.0): 1
printf("(4.0, 4.0): %d\n", classify(4.0, 4.0, 2, class_x, class_y)); // (3.0, 3.0): 0
return 0;
}
from ctypes import cdll, c_float, c_int
libcls = cdll.LoadLibrary('libclassify.A.dylib')
xmeans = (5, 2)
ymeans = (5, 2)
c_xmeans = (c_float * 2)(*xmeans)
c_ymeans = (c_float * 2)(*ymeans)
c_2 = c_int(2)
c_3p0 = c_float(3.0)
c_4p0 = c_float(4.0)
print '(3.0, 3.0): %d' % libcls.classify(c_3p0, c_3p0, c_2, c_xmeans, c_ymeans)
print '(4.0, 4.0): %d' % libcls.classify(c_4p0, c_4p0, c_2, c_xmeans, c_ymeans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment