capi.py
a,b,c=10.0,20.0,3.0
d=capi.Fcal(a,b,c) #Calculated in c language
print(a*b/c) #Calculated with python
print(d)
Execution result
capi>python capi.py
66.66666666666667
66.66666666666667
capilib.c
#include <Python.h>
static PyObject* Fcal(PyObject* self, PyObject* args){
double a,b,c,d;
if (!PyArg_ParseTuple(args, "ddd",&a,&b,&c)){
return NULL;
}
d=a*b/c;
return Py_BuildValue("d", d);
}
// Function Definition struct
static PyMethodDef myMethods[] = {
{ "Fcal",Fcal, METH_VARARGS, "Fcal a*b/c"},
{ NULL }
};
static struct PyModuleDef myModule = {
PyModuleDef_HEAD_INIT,"myModule","C API Module",-1,myMethods
};
PyMODINIT_FUNC PyInit_myModule(void){
return PyModule_Create(&myModule);
}
** Attention point is **
p.c
double a,b,c,d;
if (!PyArg_ParseTuple(args, "ddd",&a,&b,&c)){
return NULL;
}
d=a*b/c;
return Py_BuildValue("d", d);
setup.py
from distutils.core import setup, Extension
setup(name = 'myModule', version = '1.0.0', \
ext_modules = [Extension('myModule', ['capilib.c'])])
** Creating a library **
capi>python setup.py install
Recommended Posts