Cython

例一 python2环境

  • setup.py
from distutils.core import setup,Extension
exts = ([Extension('cfib2',sources=["cfib1.c","cfib1_wrap.c"])])
setup(
    ext_modules = exts,
)
  • cfib1.c
#include <Python.h>
#include "cfib1.h"
static PyObject *wrap_fib1(PyObject *self,PyObject *args)
{
    int arg;
    double result;
    if (!PyArg_ParseTuple(args,"i:fib",&arg))
        return NULL;
    result = cfib(arg);
    return Py_BuildValue("f",result);
}
static PyMethodDef func1s[] = {
    {"fib2",wrap_fib1,METH_VARARGS,"Calculate the nth fibonnaci number."},
    {NULL,NULL,0,NULL}
};
PyMODINIT_FUNC
initcfib2(void)
{
    (void) Py_InitModule("cfib2",func1s);
}
  • cfib1.c
#include "cfib1.h"

double cfib(int n) {
    int i;
    double a=0.0, b=1.0, tmp;
    for (i=0; i<n; ++i) {
        tmp = a; a = a + b; b = tmp;
    }
    return a;
}
  • cfib1.h
#ifndef __FIB_H__
#define __FIB_H__

    double cfib(int n);

#endif

python setup.py build_ext -if
import cfib2
cfib2.fib2(3)
2.0

例二
python2 `which cygdb` . -vv -- --args /usr/bin/python3 run.py

例三

Cython==0.28.0

例四 python2环境

test.c

#include<Python.h>
static PyObject *pr_isprime(PyObject *self,PyObject *args){
    int n,num;
    if(!PyArg_ParseTuple(args,"i",&num))
        return NULL;
    if(num<1){
        return Py_BuildValue("i",0);
    }
    n=num-1;
    while(n>1){
        if(num%n==0)
            return Py_BuildValue("i",0);
            n--;
    }
    return Py_BuildValue("i",1);
}

static PyMethodDef Pr1Methods[]={
    {"isPrime",pr_isprime,METH_VARARGS,"check if an input numbe is prime or not."},
    {NULL,NULL,0,NULL}
};


void initpr11111(void)
{
  (void) Py_InitModule("pr11111", Pr1Methods);
}

setup.py

from distutils.core import setup,Extension
module = Extension('pr11111',sources=['test.c'])
setup(name='Pr test',version = '1.0',ext_modules=[module])

例五 python3环境
readfile.c

#define PY_SSIZE_T_CLEAN

#include <Python.h>

static PyObject *method_fputs(PyObject *self,PyObject *args){
    char *str,*filename = NULL;
    int bytes_c = -1;

    if (!PyArg_ParseTuple(args,"ss",&str,&filename)){
        return NULL;
    }

    FILE *fp = fopen(filename,"w");
    bytes_c = fputs(str,fp);
    fclose(fp);
    return (PyObject *)Py_BuildValue("i",bytes_c);
}

static PyMethodDef FputsMethods[] = {
    {"fputs",method_fputs,METH_VARARGS,"docstring"},
    {NULL,NULL,0,NULL}
};

static struct PyModuleDef fputsmodule = {
    PyModuleDef_HEAD_INIT,
    "fputs",
    "Python interface for the fputs C library function",
    -1,
    FputsMethods
};

PyMODINIT_FUNC PyInit_fputs(void) {
    return PyModule_Create(&fputsmodule);
}

mufunc.cpp

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int myfputs(char *content,char *filename){
    FILE *fp = fopen(filename,"w");
    fputs(content,fp);
    fclose();
    return 0;
}

setup.py

from distutils.core import setup, Extension

def main():
    setup(name="fputs",
          version="1.0.0",
          description="Python interface for the fputs C library function",
          author="hanbing",
          author_email="beatmight@gmail.com",
          ext_modules=[Extension("fputs", ["readfile.c"])])

if __name__ == "__main__":
    main()

python3 setup.py build_ext -i
import fputs
fputs.fputs(“阿四达aa”,“1.txt”)

例六 python3环境
readfile1.c

#define PY_SSIZE_T_CLEAN
#include <Python.h>
static PyObject *method_fputs(PyObject *self, PyObject *args, PyObject *kw) {
    char *str, *filename = NULL;
    int bytes_copied = -1;

    /* Parse arguments */
    // 设置两个参数的keywords分别为 content,filename
    char *kwlist[] = {"content", "filename", NULL};
    if(!PyArg_ParseTupleAndKeywords(args, kw, "ss", kwlist, &str, &filename)) {
        return NULL;
    }

    FILE *fp = fopen(filename, "w");
    bytes_copied = fputs(str, fp);
    fclose(fp);

    return (PyObject *)Py_BuildValue("i", bytes_copied);
}

static PyMethodDef FputsMethods[] = {
    {"fputs", method_fputs, METH_VARARGS | METH_KEYWORDS, "Python interface for fputs C library function"},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef fputsmodule = {
    PyModuleDef_HEAD_INIT,
    "fputs",
    "Python interface for the fputs C++ library function",
    -1,
    FputsMethods
};

PyMODINIT_FUNC PyInit_fputs(void) {
    return PyModule_Create(&fputsmodule);
}

setup.py

from distutils.core import setup, Extension

def main():
    setup(name="fputs",
          version="1.0.0",
          description="Python interface for the fputs C library function",
          author="hanbing",
          author_email="beatmight@gmail.com",
          ext_modules=[Extension("fputs", ["readfile1.c"])])

if __name__ == "__main__":
    main()

python3 setup.py build_ext -i
import fputs
fputs.fputs(“阿四达aa”,filename=“1.txt”)

例七 python3环境
readfile2.c

#define PY_SSIZE_T_CLEAN
#include <Python.h>

static PyObject *StringTooShortError = NULL;

static PyObject *method_fputs(PyObject *self, PyObject *args, PyObject *kw) {
    char *str, *filename = NULL;
    int bytes_copied = -1;

    /* Parse arguments */
    char *kwlist[] = {"content", "filename", NULL};
    if(!PyArg_ParseTupleAndKeywords(args, kw, "ss", kwlist, &str, &filename)) {
        return NULL;
    }
    if (strlen(str) < 10) {
        /* Passing custom exception */
        PyErr_SetString(StringTooShortError, "String length must be greater than 10");
        return NULL;
    }

    FILE *fp = fopen(filename, "w");
    bytes_copied = fputs(str, fp);
    fclose(fp);

    return (PyObject *)Py_BuildValue("i", bytes_copied);
}

static PyMethodDef FputsMethods[] = {
    {"fputs", method_fputs, METH_VARARGS | METH_KEYWORDS, "Python interface for fputs C library function"},
    {NULL, NULL, 0, NULL}
};


static struct PyModuleDef fputsmodule = {
    PyModuleDef_HEAD_INIT,
    "fputs",
    "Python interface for the fputs C library function",
    -1,
    FputsMethods
};


PyMODINIT_FUNC PyInit_fputs(void) {

        /* Assign module value */
    PyObject *module = PyModule_Create(&fputsmodule);

    /* Initialize new exception object */
    StringTooShortError = PyErr_NewException("fputs.StringTooShortError", NULL, NULL);

    /* Add exception object to your module */
    PyModule_AddObject(module, "StringTooShortError", StringTooShortError);

    return module;
}

setup.py

from distutils.core import setup, Extension

def main():
    setup(name="fputs",
          version="1.0.0",
          description="Python interface for the fputs C library function",
          author="hanbing",
          author_email="beatmight@gmail.com",
          ext_modules=[Extension("fputs", ["readfile2.c"])])

if __name__ == "__main__":
    main()

例八 python2
example.c

#include <Python.h>

static PyObject* example_mul(PyObject* self, PyObject*args)
{
    float a, b;
    if(!PyArg_ParseTuple(args, "ff", &a, &b))
    {
        return NULL;
    }
    return Py_BuildValue("f", a*b);
}

static PyObject* example_div(PyObject* self, PyObject*args)
{
    float a, b;
    if(!PyArg_ParseTuple(args, "ff", &a, &b))
    {
        return NULL;
    }
    return Py_BuildValue("f", a/b);  // to deal with b == 0
}

static char mul_docs[] = "mul(a, b): return a*b\n";
static char div_docs[] = "div(a, b): return a/b\n";

static PyMethodDef example_methods[] =
{
    {"mul", (PyCFunction)example_mul, METH_VARARGS, mul_docs},
    {"div", (PyCFunction)example_div, METH_VARARGS, div_docs},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initexample(void)
{
    Py_InitModule3("example", example_methods, "Extension module example!");
}

setup.py

from distutils.core import setup, Extension
setup(name="exampleAPP", version="1.0", ext_modules=[Extension("example", ["example.c"])])

例九 python3
testmodule.c

#include<Python.h>
static PyObject *method_sum_list_u64(PyObject *self,PyObject *args);

static PyObject *method_sum_list_u64(PyObject *self,PyObject *args){
    uint64_t sum = 0;
    PyObject *input_list;

    if(!PyArg_ParseTuple(args,"O!",&PyList_Type,&input_list)){
        return NULL;
    }

    Py_ssize_t data_points = PyList_Size(input_list);

    for(Py_ssize_t i=0;i<data_points;i++){
        PyObject *item = PyList_GetItem(input_list,i);
        sum += PyLong_AsUnsignedLongLong(item);
    }
    return PyLong_FromUnsignedLongLong(sum);//PyLong_AsLongLong
}

static PyMethodDef testmodule1Method[] = {
    {"sum_list_u64",method_sum_list_u64,METH_VARARGS,"docs"},
    {NULL,NULL,0,NULL}
};

static struct PyModuleDef testmodule = {
    PyModuleDef_HEAD_INIT,
    "testmodule",
    "docs",
    -1,
    testmodule1Method
};

PyMODINIT_FUNC PyInit_testmodule(void){
    return PyModule_Create(&testmodule);
}

setup.py

from setuptools import setup,Extension
def main():
    setup(name="testmodule",
          version="1.0.1",
          description="Python interface for the testmodule C library function",
          ext_modules=[Extension("testmodule", ["testmodule.c"])])

if __name__ == "__main__":
    main()

import testmodule
import numpy as np
input_list = [np.int(1000),123]#input_list = [np.uint64(1000)]
print(testmodule.sum_list_u64(input_list))
1123

例九 python2 and numpy
cos_module_np.c

#include <Python.h>
#include <numpy/arrayobject.h>
#include <math.h>

static PyObject* cos_func_np(PyObject* self,PyObject* args)
{
    PyArrayObject *in_array;
    PyObject *out_array;
    PyArrayIterObject *in_iter;
    PyArrayIterObject *out_iter;
    if (!PyArg_ParseTuple(args,"O!",&PyArray_Type,&in_array)){
        return NULL;
    }
    out_array = PyArray_NewLikeArray(in_array,NPY_ANYORDER,NULL,0);
    if(out_array == NULL)
        return NULL;

    in_iter = (PyArrayIterObject *)PyArray_IterNew((PyObject*)in_array);
    out_iter = (PyArrayIterObject *)PyArray_IterNew(out_array);
    if (in_iter == NULL || out_iter == NULL)
        goto fail;

    while(in_iter->index < in_iter->size && out_iter->index < out_iter->size){
        double * in_dataptr = (double *)in_iter->dataptr;
        double * out_dataptr = (double *)out_iter->dataptr;
        *out_dataptr = cos(*in_dataptr);
        PyArray_ITER_NEXT(in_iter);
        PyArray_ITER_NEXT(out_iter);
    }
    Py_DECREF(in_iter);
    Py_DECREF(out_iter);
    Py_INCREF(out_array);
    return out_array;

    fail:
        Py_XDECREF(out_array);
        Py_XDECREF(in_iter);
        Py_XDECREF(out_array);
        return NULL;
}

static PyMethodDef CosMethods[] =
{
    {"cos_func_np",cos_func_np,METH_VARARGS,"evalxxx"},
    {NULL,NULL,0,NULL}
};

PyMODINIT_FUNC initcosmodulenp(void){
    (void) Py_InitModule("cosmodulenp",CosMethods);
    import_array();
}

setup.py

from distutils.core import setup ,Extension
import numpy
cos_module_npp = Extension('cosmodulenp',sources=['cos_module_np.c'],include_dirs=[numpy.get_include()])
setup(ext_modules=[cos_module_npp])

例十 python2 and ctypes
cos_doubles.c

#include <math.h>
void cos_doubles(double * in_array,double * out_array,int size){
    int i;
    for(i=0;i<size;i++){
        out_array[i] = cos(in_array[i]);
    }
}

cos_doubles.h

void cos_dounles(double * in_array,double *out_array,int size);

cos_doubles.py

import numpy as np
import numpy.ctypeslib as npct
import pylab
import cos_doubles
from ctypes import c_int

array_1d_double = npct.ndpointer(dtype=np.double,ndim=1,flags = 'CONTIGUOUS')

libcd = npct.load_library("libcos_doubles",".")

libcd.cos_doubles.restype = None
libcd.cos_doubles.argtypes = [array_1d_double,array_1d_double,c_int]

def cos_doubles_func(in_array,out_array):
    return libcd.cos_doubles(in_array,out_array,len(in_array))

x = np.arange(0,2*np.pi,0.1)
y = np.empty_like(x)

cos_doubles.cos_doubles_func(x,y)
pylab.plot(x,y)
pylab.show()

makefile

libcos_doubles.so:cos_doubles.o
	gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o
cos_doubles.o : cos_doubles.c
	gcc -c -fPIC cos_doubles.c -o cos_doubles.o
clean:
	-rm -vf libcos_doubles.so cos_doubles.pyc cos_doubles.o
m.PHONY:clean

ctypes测试

import ctypes
from ctypes.util import find_library

libm = ctypes.cdll.LoadLibrary(find_library('m'))
libm.cos.argtypes = [ctypes.c_double]
libm.cos.restype = ctypes.c_double

def cos_func(arg):
    return libm.cos(arg)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值