How to get Python to use Assembly

前端 未结 3 836
死守一世寂寞
死守一世寂寞 2021-02-05 13:43

I am a beginner in assembly, but a master in Python. I have just recently started to learn x86_64 NASM for windows, and I wish to combine the power of assembly, and the flexibil

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 14:46

    You could create a C extension wrapper for the functions implemented in assembly and link it to the OBJ file created by nasm.

    A dummy example (for 32 bit Python 2; not tested):

    myfunc.asm:

    ;http://www.nasm.us/doc/nasmdoc9.html
    global  _myfunc 
    section .text
    _myfunc: 
        push    ebp 
        mov     ebp,esp 
        sub     esp,0x40        ; 64 bytes of local stack space 
        mov     ebx,[ebp+8]     ; first parameter to function 
        ; some more code 
        leave
        ret
    

    myext.c:

    #include 
    
    void myfunc(void);
    
    static PyObject*
    py_myfunc(PyObject* self, PyObject* args)
    {
        if (!PyArg_ParseTuple(args, ""))
            return NULL;
        myfunc();
        Py_RETURN_NONE;
    }
    
    static PyMethodDef MyMethods[] =
    {
        {"myfunc", py_myfunc, METH_VARARGS, NULL},
        {NULL, NULL, 0, NULL}
    };
    
    PyMODINIT_FUNC initmyext(void)
    {
        (void) Py_InitModule("myext", MyMethods);
    }
    

    setup.py:

    from distutils.core import setup, Extension
    setup(name='myext', ext_modules=[
        Extension('myext', ['myext.c'], extra_objects=['myfunc.obj'])])
    

    Build and run:

    nasm -fwin32 myfunc.asm

    python setup.py build_ext --inplace

    python -c"import myext;myext.myfunc()"

提交回复
热议问题