Python 調用 C 動態庫


細節

  1. 調用C庫而不是C++庫
  2. 要注意平台位數對應
  3. 解釋型語言自上而下執行
  4. 函數類似標簽,縮進表示代碼塊
  5. 一行一條語句時可以不用分號
  6. 如何分配一段內存等

代碼

"""
test python sample
"""

# 輸入輸出
print("hello ", end=" ")
print("python!")
string = input("請輸入:")
print("你輸入的內容是: ", string)

# 定義函數
def sample_function(a, b):
    print("This is a function .")
    return a+b

# 條件控制
def sample_conditions():
    val = -2
    if val == 0:
        print ("val == 0")
    elif val >= 1:
        print ("val >= 1")
    else:
        print ("val < 0")

# 循環語句
def sample_loop():
    n = 100
    i = 0
    while i <= n:
        print(i, end=',')
        i += 1
    print()


# 引入C庫
import ctypes
#lib = ctypes.CDLL("./libmath.so")
lib = ctypes.CDLL("./Dll1.dll")
def sample_c_dll():
    val = lib.add(3, 5)
    print ("val == ", val)
    ubuff = ctypes.create_string_buffer(64)
    val = lib.get_64byte_content(ctypes.byref(ubuff))
    print ("string == ", bytes.decode(ubuff.value))


# 函數調用
sample_function(1, 2)
sample_conditions()
sample_loop()
sample_c_dll()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM