python調用C動態庫,結果返回結構體如何處理;
#!/bin/env python
# coding=UTF-8
from ctypes import *
class Hardware_API_Result(Structure):
_fields_ = [ ("result", c_int),("json", c_char * 256)]
class GetCFunc:
"""
結構體賦參數
#test_struct = PyTestStruct()
#test_struct.result = 1
#test_struct.json = 'Hello, C'.encode() # Python 2.x 則不需要寫 encode
"""
def __init__(self):
self.cdll = cdll.LoadLibrary('libhardwareInfo2.so')
return
def getSysTime(self):
"""
獲取系統時間
:return:
"""
#指定方法的返回類型
self.cdll.get_system_time.restype = (Hardware_API_Result)
p = self.cdll.get_system_time()
#接收指針結構體
# func.argtypes = [POINTER(PyTestStruct)]
#print(type(p))
print("json=",p.json)
print(p.result)
# print(type(p.json))
if p.result==0:
#返回的bytes類型,轉變爲str類型
return str( p.json, encoding = "utf-8")
else:
return "404"
def start4G(self):
"""啓動4g"""
self.cdll.start_4g.restype = c_int
p = self.cdll.start_4g()
return p
def getWiredNetInfo(self):
"""獲取有線配置信息"""
self.cdll.get_wired_net_info.restype = (Hardware_API_Result)
p = self.cdll.get_wired_net_info()
if p.result == 0:
# 返回的bytes類型,轉變爲str類型
return str(p.json, encoding="utf-8")
else:
return "404"
def ping(self,ip):
"""ping 輸入ip 是否同,返回值爲0,通的"""
self.cdll.ping.restype = (Hardware_API_Result)
p = self.cdll.ping(bytes(ip,encoding="utf-8"))
return p.result
def doReboot(self):
"""重啓"""
self.cdll.do_reboot()