capi.py
a,b,c=10.0,20.0,3.0
d=capi.Fcal(a,b,c) #Berechnet in c Sprache
print(a*b/c) #Mit Python berechnet
print(d)
Ausführungsergebnis
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);
}
** Aufmerksamkeitspunkt ist **
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'])])
** Erstellen einer Bibliothek **
capi>python setup.py install