@DaviDOSik

Как объявить массив структур в Python (cypyton)?

В общем проблема вот в чем.Есть некая библиотека которая импортирует структуры из С библиотеки с помощью ctypes.

Библиотека тут python_j2534

В питоне соответственно создается класс структуры...
import ctypes as ct
 
from J2534.dllLoader import MyDll
PassThru_Data = (ct.c_ubyte * 4128)
class PassThru_Msg(ct.Structure):
    _fields_ = [
        ("ProtocolID", ct.c_ulong),
        ("RxStatus", ct.c_ulong),
        ("TxFlags", ct.c_ulong),
        ("Timestamp", ct.c_ulong),
        ("DataSize", ct.c_ulong),
        ("ExtraDataIndex",ct.c_ulong),
        ("Data", PassThru_Data)]


Вот тут эта структура наследуется классами :

ptData = PassThru_Data
class baseMsg(PassThru_Msg):
    def _setData(self, data):
        print (data)
        self.DataSize = len(data)
        self.Data = ptData()
        for i in range(self.DataSize):
            self.Data[i] = data[i]
    def setID(self, ID):
        d = Func.IntToID(ID)
        self._setData(d)
    def setIDandData(self, ID, data = []):
        d = Func.IntToID(ID) + data
        self._setData(d)</spoiler>
 
class pt15765Msg(baseMsg):
    def __init__(self, TxFlag):
        self.ProtocolID = ProtocolID.ISO15765
        self.TxFlags = TxFlag
class ptMskMsg(pt15765Msg):
    pass
class ptPatternMsg(pt15765Msg):
    pass
class ptFlowControlMsg(pt15765Msg):
    pass
class ptTxMsg(baseMsg):
    def __init__(self, ProtocolID, TxFlags):
        self.ProtocolID = ProtocolID
        self.TxFlags = TxFlags
class ptRxMsg(baseMsg):
    def show(self):
        print(self.ProtocolID, self.RxStatus, self.Data[:self.DataSize])

Потом в файле я создаю переменную структуры и могу передавать её в функцию, использующую её, и назад функция мне возвращает массив данных в ней :

msg = J2534.ptRxMsg()
print(msg.Data[:100])


Это работает только для одного сообщения...в документации к библиотеки которая на написана на C есть такая выдержка
:

The PassThruWriteMsgs function is used to transmit network protocol messages over an existing logical
communication channel. The network protocol messages will flow from the User Application to the
PassThru device.
long PassThruWriteMsgs(
 unsigned long ChannelID,
 PASSTHRU_MSG *pMsg,
 unsigned long *pNumMsgs,
 unsigned long Timeout
);

Parameters
ChannelID
The logical communication channel identifier assigned by the J2534 API/DLL when the communication
channel was opened via the PassThruConnect function.
pMsg
Pointer to the message structure containing the UserApplication transmit message(s).
For sending more than one message, this must be a pointer to an array of PASSTHRU_MSG structures.
Refer to PASSTHRU_MSG structure definition on page 46.

PNumMsgs
Pointer to the variable that contains the number of PASSTHRU_MSG structures that are allocated for
transmit frames. On function completion this variable will contain the actual number of messages sent to
the vehicle network. The transmitted number of messages may be less than the number requested by the
UserApplication.
Timeout
Timeout interval(in milliseconds) to wait for transmit completion. A value of zero instructs the API/DLL
to queue as many transmit messages as possible and return immediately. A nonzero timeout value
instructs the API/DLL to wait for the timeout interval to expire before returning. The API/DLL will not
wait the entire timeout interval if an error occurs or the specified number of messages have been sent.


Как я понимаю для того чтоб получить больше чем одно сообщение мне нужно объявить массив структур

В C это делается так :
PASSTHRU_MSG Msg[2];

и потом я могу обращаться вот так :
msg[0].Data[12]

В Python я делаю вот так и оно работает :
print(msg.Data[:100])

А когда делаю так он мне дает понять что такое невозможно :
print(msg[0].Data[:100])

Собственно как мне объявить эту переменную в Python как массив структур чтоб все заработало как в Cи.?


P.S Надеюсь объяснил доходчиво...
  • Вопрос задан
  • 352 просмотра
Решения вопроса 1
@DaviDOSik Автор вопроса
msg = (PassThru_Msg * 3)()
     pMsg = ctypes.cast(msg, ctypes.POINTER(PassThru_Msg))

     numMsgs = ctypes.c_ulong(3)
     pNumMsgs = ctypes.pointer(numMsgs)
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы