将指针传递给方法之间的第一个数据包(Obj-C)

时间:2012-01-05 19:33:35

标签: objective-c pointers coremidi

我在这里遗漏了一些东西,但我不确定如何解决它。第一个版本有效:

- (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];
}

对于DRYness,我尝试从创建数据包列表中创建一个方法:

- (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];
}

现在sendPacketList方法因EXC_BAD_ACCESS而失败。使用GDB,即使packetList ...

sendPacketList仍然看起来很好

Looking at the docs,似乎我传递的东西只是指向列表中第一个数据包的指针。那么......我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

问题是Byte packetBuffer[size+100]声明了一个本地数组,在该方法退出后不能访问该数组。你有两个选项(我将其作为函数编写):

选项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;
}

如果你这样做,你以后必须free()缓冲区,这是一种痛苦。

选项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;
}

在这种情况下,您必须在函数外部声明Byte packetBuffer[size + 100]并将其作为第一个参数传递,这也有点不方便。