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()
posted @ 2020-09-12 09:10  派大海星  阅读(928)  评论(0编辑  收藏  举报