Pass Pointer to First Packet Between Methods (Obj-C)

孤者浪人 提交于 2019-12-25 06:48:57

问题


I'm missing something here, but I'm not sure how to fix it. The first version of this works:

- (void) sendBytes:(const UInt8*)bytes size:(UInt32)size
{
    Byte packetBuffer[size+100];
    MIDIPacketList *packetList = (MIDIPacketList*)packetBuffer;
    MIDIPacket     *packet     = MIDIPacketListInit(packetList);
    MIDIPacketListAdd(packetList, sizeof(packetBuffer), packet, 0, size, bytes);
    [self sendPacketList:packetList];
}

For DRYness, I try to make a method out of the packet list creation:

- (MIDIPacketList*) makePacketList:(const UInt8*)data size:(UInt32)size
{
    Byte packetBuffer[size+100];
    MIDIPacketList *packetList = (MIDIPacketList*)packetBuffer;
    MIDIPacket     *packet     = MIDIPacketListInit(packetList);
    MIDIPacketListAdd(packetList, sizeof(packetBuffer), packet, 0, size, data);
    return packetList;
}


- (void) sendBytes:(const UInt8*)bytes size:(UInt32)size
{
    MIDIPacketList *packetList = [self makePacketList:bytes size:size];
    [self sendPacketList:packetList];
}

And now the sendPacketList method fails with an EXC_BAD_ACCESS. Using GDB, the packetList still looks good even within sendPacketList...

Looking at the docs, it seems that the thing I'm passing around is just a pointer to the first packet in the list. So... how can I do this?


回答1:


The trouble is that Byte packetBuffer[size+100] declares a local array, which must not be accessed after that method exits. You have two options (which I'll write as functions):

Option 1:

MIDIPacketList *makePacketList(const UInt8 *data, UInt32 size) {
    Byte *packetBuffer = malloc(size + 100);
    MIDIPacketList *packetList = (MIDIPacketList*)packetBuffer;
    MIDIPacket     *packet     = MIDIPacketListInit(packetList);
    MIDIPacketListAdd(packetList, sizeof(packetBuffer), packet, 0, size, data);
    return packetList;
}

If you do it this way, you'll have to free() the buffer later on, which is kind of a pain.

Option 2:

MIDIPacketList *makePacketList(Byte *packetBuffer, const UInt8 *data, UInt32 size) {
    MIDIPacketList *packetList = (MIDIPacketList*)packetBuffer;
    MIDIPacket     *packet     = MIDIPacketListInit(packetList);
    MIDIPacketListAdd(packetList, size + 100, packet, 0, size, data);
    return packetList;
}

In this case, you'll have to declare the Byte packetBuffer[size + 100] outside of the function and pass it in as the first argument, which is also somewhat inconvenient.



来源:https://stackoverflow.com/questions/8748582/pass-pointer-to-first-packet-between-methods-obj-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!