C function in a Python context

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • castironpi@gmail.com

    C function in a Python context

    To write quick C things that Python won't do up to speed. So it's got
    a redundancy.

    import ext
    extA= ext.Ext()
    extA[ 'enumfactors' ]= r"""
    int enumfactors( int a, const char* sep ) {
    int ret= 0, i;
    for( i= 1; i<= a; i++ ) {
    if( a% i== 0 ) {
    ret+= 1;
    if( i1 ) {
    printf( "%s", sep );
    }
    printf( "%i", i );
    }
    }
    printf( "\n" );
    return ret;
    }
    """, ("i","i","s" )

    factorsn= extA.enumfactor s( 209677683, ', ' )
    print( "%i factors total."% factorsn )

    import sys
    sys.exit()


    1, 3, 23, 69, 131, 393, 3013, 9039, 23197, 69591, 533531, 1600593,
    3038807, 9116
    421, 69892561, 209677683
    16 factors total.
  • castironpi@gmail.com

    #2
    Re: C function in a Python context

    #include <string>
    #include <vector>
    This modification required:

    compilercommand = 'c:/programs/mingw/bin/g++'

    and

    strctypes= { 'i': 'int', 's': 'const char*',
    'O': 'PyObject*' }

    The output is:

    #include <c:/programs/python/include/Python.h>

    [ user code ]

    static PyObject *
    extcode_enumfac tors(PyObject *self, PyObject *args) {
    PyObject* result;
    int arg0;
    const char* arg1;
    PyArg_ParseTupl e(args, "is", &arg0, &arg1 );
    result= enumfactors( arg0, arg1 );
    return Py_BuildValue( "O", result );
    }

    static PyMethodDef ExtcodeMethods[] = {
    { "enumfactor s", extcode_enumfac tors, METH_VARARGS, "" },
    {NULL, NULL, 0, NULL}
    };

    PyMODINIT_FUNC
    initextcode(voi d) {
    (void) Py_InitModule(" extcode", ExtcodeMethods) ;
    }

    The benefits are automatic parameter parsing and automatic method
    table construction. The costs are portability and parameter parsing
    flexibility. Add up.

    Comment

    Working...