python調用c的方法

來源:互聯網
上載者:User

python調用c的方法研究了三天,今天看了一篇部落格
原來這麼簡單,可能是最簡單的方法了吧。下面整理一下思路

實驗平台:
window xp系統,編譯環境是vs2005

實驗步驟:
步驟1:
在vs2005下編寫c模組
代碼如下

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include "Python.h"

_declspec(dllexport) int fac(int n)
{
printf("fac fn run.\n");
if(n < 2)
return 1;
return n * fac(n - 1);
}

步驟2:
編譯產生dll庫

步驟3:
在python中載入動態庫並測試。
代碼如下
def test_py_call_clib():
    from ctypes import *
    import os
    test_other = cdll.LoadLibrary(os.getcwd() + '/test_other.dll')
    print "load library success."
    print test_other.fac(4)

if __name__ == "__main__":
test_py_call_clib()

注意載入動態庫的目錄

參考

http://coolshell.cn/articles/671.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.