Last active
December 17, 2015 10:48
-
-
Save haiiro-shimeji/5597174 to your computer and use it in GitHub Desktop.
Sample that describe how to call c function from python, and how to give float array.
This file contains hidden or 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
| PYTHON_VERSION=2.7 | |
| CCFLAG=-std=gnu99 -Wall -fPIC -I/usr/include/python${PYTHON_VERSION} | |
| LDFLAG=-lpython${PYTHON_VERSION} | |
| run: build | |
| python -m unittest pythonc_test | |
| build: spam.so | |
| spam.so: spam.o | |
| gcc -shared -o $@ $^ ${LDFLAG} | |
| .c.o: | |
| gcc -c ${CCFLAG} $^ | |
| clean: | |
| rm -f spam.o spam.so |
This file contains hidden or 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 unittest | |
| import spam | |
| class PythonCTest(unittest.TestCase): | |
| def test(self): | |
| self.assertEquals(6, spam.sum(3, [1, 2, 3])) | |
| if __name__ == '__main__': | |
| unittest.main() |
This file contains hidden or 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
| #include<Python.h> | |
| static float* create_array(PyObject*); | |
| static void dispose_array(float*); | |
| static PyObject * | |
| sum(PyObject *self, PyObject *args) | |
| { | |
| int num; | |
| PyObject *obj; | |
| float sum = 0; | |
| if (!PyArg_ParseTuple( | |
| args, "iO!", | |
| &num, | |
| &PyList_Type, &obj)) { | |
| return NULL; | |
| } | |
| float* a = create_array(obj); | |
| for (int i=0; num > i; ++i) { | |
| sum += a[i]; | |
| } | |
| dispose_array(a); | |
| return Py_BuildValue("f", sum); | |
| } | |
| static float* create_array(PyObject* listObj) { | |
| int numLines = PyList_Size(listObj); | |
| if (numLines < 0) return NULL; | |
| float *result = (float*)malloc(sizeof(float) * numLines); | |
| for (int i=0; i<numLines; i++){ | |
| PyObject *obj = PyList_GetItem(listObj, i); | |
| result[i] = (float)(PyFloat_AsDouble(obj)); | |
| } | |
| return result; | |
| } | |
| static void dispose_array(float* a) { | |
| free(a); | |
| } | |
| static PyMethodDef methods[] = { | |
| {"sum", (PyCFunction)sum, METH_VARARGS, "calculate sum.\n"}, | |
| {NULL, NULL, 0, NULL} | |
| }; | |
| void initspam(void) | |
| { | |
| Py_InitModule3("spam", methods, ""); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment