Python 呼叫 C 動態庫

2022-06-18 15:06:12 字數 1224 閱讀 3598

呼叫c庫而不是c++庫

要注意平台位數對應

解釋型語言自上而下執行

函式類似標籤,縮排表示**塊

一行一條語句時可以不用分號

如何分配一段記憶體等

"""

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()

python呼叫C語言動態庫

python完美相容c語言,有了ctypes 可以呼叫c相關 如果是c 編譯的時候加上 extern c 就可以了 如果是一些複雜型別比如結構體,類,聯合一些 可以考慮用boost.python exp.c include int add int a,int b 編譯生成動態庫add.so gcc ...

python呼叫c 動態庫(1)

由於專案中需要使用python語言搭建伺服器呼叫我的目標檢測演算法來實現功能,所以記錄一下自己除錯過程中的歷程,也做個mark。1.準備c 動態庫 ifndef cppde h define cppde h include cppde global.h include include include...

python呼叫c動態庫方法練習

練習1 python在不使用import ctypes方式呼叫c語言動態庫的練習,include include include include int sum int a,int b c語言實現的功能 pyobject wrap sum1 pyobject self,pyobject args 呼...