zoukankan      html  css  js  c++  java
  • PYTHON调用C接口(基于Ctypes)实现stein算法最大公约数的计算

    相关环境配置

    • mingw,选择相应的32位、64位的版本,主要用于编译动态链接库dll文件,可用vs替代,这里我选择轻量级的mingw
    • windows64位地址:https://sourceforge.net/projects/mingw-w64/
    • 安装过程中 Architecture选项选择X86_64,其他默认即可,把安装好的mingw的bin目录加入环境配置的PATH列表

    一、编写C函数

    /*最大公约数算法*/
    
    unsigned int gcd(unsigned int a,unsigned int b)
    { unsigned
    int k=1; if (a==0) return b; else if (b==0) return a; while((!(a&1))&&(!(b&1))){ k<<=1; a>>=1; b>>=1; } while(!(a&1))a>>=1; while(!(b&1))b>>=1; if(a<b) a^=b,b^=a,a^=b; while(a!=b){ a-=b; if(a<b) a^=b,b^=a,a^=b; } return k*a; }

    二、编译动态链接库

    为了编译成动态链接库,在入相应导出动态链接库的代码,完成后保存为.c的c文件,本例保存为 stein_gcd.c

    /*最大公约数算法*/
    
    #ifdef _MSC_VER
        #define DLL_EXPORT __declspec( dllexport ) 
    #else
        #define DLL_EXPORT
    #endif
     
    DLL_EXPORT unsigned int gcd(unsigned int a,unsigned int b){
        /*...省略上述c代码块*/
    }

    在c文件目录打开powshell,执行命令

    gcc -m64 -fPIC -shared -msse4  stein_gcd.c -o stein_gcd.dll

    完成后会得到动态链接库  stein_gcd.dll

    三、PYTHON调用动态链接库

    用Ctypes调用dll

    from ctypes import *
    steingcd = cdll.LoadLibrary('stein_gcd.dll')#dll参数是dll的路径
    print(steingcd.gcd(39,26))

    简单的demo就完成了。更多细致的比如Ctypes的各类型连接python和c时对应的数据类型,则去细致的翻看ctypes文档,当然也还有更多的方法,比如直接编译成python直接调用的库,懒先不写了

  • 相关阅读:
    【VectorDemo】
    【列表迭代器:添加元素】
    【列表迭代器】
    【迭代器】
    【LinkedList】
    【list 集合的使用】
    【CollectionDemo2】
    【CollectionDemo1】
    【集合和数组的区别?】
    【到底使用那种集合?】
  • 原文地址:https://www.cnblogs.com/shld/p/10194780.html
Copyright © 2011-2022 走看看