日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Python調(diào)用C

系統(tǒng) 1678 0

文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|?

1. 引言

眾所周知,Python語言簡單、易學(xué)、開源、具有豐富的庫,Python的第一個編譯器是用C語言實(shí)現(xiàn)的。但Python的缺點(diǎn)也非常明顯,最讓人詬病的就是Python的性能問題。因此,為了提高程序的運(yùn)行效率,通常會將程序的關(guān)鍵部分使用C或C++重寫,編譯成動態(tài)鏈接庫,然后在Python(CPython)中進(jìn)行調(diào)用。運(yùn)行環(huán)境:Ubuntu 16.04、Python 2.7、Python 3.5。

2. Python C擴(kuò)展

2.1 普通C函數(shù)

          
            void hello()
{
    printf("Hello World!\n");
}

int add(int a, int b)
{
    return a + b;
}

          
        

2.2 Python C擴(kuò)展

Python擴(kuò)展模塊由以下幾部分組成:

  • 頭文件
  • 調(diào)用的C函數(shù)
  • 模塊方法表
  • 模塊初始化函數(shù)

具體實(shí)現(xiàn) demo.c 如下:

          
            // 包含Python頭文件
#include 
            
              


// 兼容Python3
#if PY_MAJOR_VERSION >= 3
#define PYTHON3
#endif


// hello函數(shù)實(shí)現(xiàn)
static PyObject* hello(PyObject *self, PyObject *args)
{
    printf("Hello World\n");
    return Py_None;
}


// add函數(shù)實(shí)現(xiàn)
static PyObject* add(PyObject *self, PyObject *args)
{
    int a, b;
    if(!PyArg_ParseTuple(args, "ii", &a, &b))
    {
        return NULL;
    }
    return Py_BuildValue("i", a + b);
}


// 模塊方法表
static PyMethodDef TwoMethods[] = {
    { "hello", hello, METH_NOARGS, "Print Hello" },
    { "add", add, METH_VARARGS, "Add two integers"},
    { NULL, NULL, 0, NULL }
};


#ifdef PYTHON3
// Python3模塊定義結(jié)構(gòu)體
static struct PyModuleDef testModule = {
    PyModuleDef_HEAD_INIT,
    "testModule",
    "Test Module",
    -1,
    TwoMethods
};


// Python3模塊初始化函數(shù)
PyMODINIT_FUNC PyInit_demo(void)
{
    return PyModule_Create(&testModule);
}


#else
// Python2模塊初始化函數(shù)
PyMODINIT_FUNC initdemo(void)
{
    Py_InitModule("demo", TwoMethods);
}
#endif

            
          
        

2.3 編譯并測試

編寫 setup.py 文件:

          
            from distutils.core import setup, Extension

demo = Extension('demo', sources = ['demo.c'])

setup(name = 'C extension module', version = '1.0', description = 'This is a demo', ext_modules = [demo])

          
        

生成動態(tài)鏈接庫的命令如下:

          
            #python2
$ python setup.py build_ext --inplace
running build_ext
building 'demo' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c demo.c -o build/temp.linux-x86_64-2.7/demo.o
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wl,-Bsymbolic-functions -Wl,-z,relro -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/demo.o -o /workspace/python-c/demo.so

#python3
$ python3 setup.py build_ext --inplace
running build_ext
building 'demo' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c demo.c -o build/temp.linux-x86_64-3.5/demo.o
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.5/demo.o -o /workspace/python-c/demo.cpython-35m-x86_64-linux-gnu.so

          
        

hello , add 函數(shù)測試:

          
            >>> from demo import hello, add
>>> hello()
Hello World
>>> add(2, 3)
5

          
        

參考資料

  1. https://www.cnblogs.com/vamei/archive/2013/02/06/2892628.html
  2. https://www.yanxurui.cc/posts/python/2017-06-18-3-ways-of-calling-c-functions-from-python/
  3. https://swe.mirsking.com/languages/python/pythoncallcplusplus
  4. https://www.jianshu.com/p/cd28e8b0cce1
  5. https://docs.python.org/2.7/extending/extending.html
  6. https://docs.python.org/2.7/extending/building.html
  7. https://tutorialedge.net/python/python-c-extensions-tutorial/

更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦?。。?/p>

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 大洼县| 盐边县| 武威市| 安仁县| 称多县| 郴州市| 木兰县| 鄯善县| 广平县| 德昌县| 牙克石市| 府谷县| 大庆市| 齐齐哈尔市| 宜都市| 清镇市| 绥阳县| 东乌| 巴里| 民勤县| 永寿县| 宁强县| 灌阳县| 惠东县| 宜良县| 游戏| 台安县| 含山县| 获嘉县| 东海县| 宁波市| 博野县| 东莞市| 含山县| 吉隆县| 南澳县| 南宫市| 启东市| 澜沧| 四会市| 保山市|