所以我正在尝试制作一个缓冲区类。该缓冲区类包含一个大小为384 * 4的巨大缓冲区。该计划是针对每个收到的UDP数据报,大小为384,调用缓冲区类并返回一个指向应将数据报写入位置的指针。
将有另一个侦听器指针,RtAudio播放将从该侦听器指向。 [聆听部分并不完全相关,因为我在写入缓冲区时仍然遇到问题]
当我尝试调用server _-> getPointer()(如下所示)时,出现“异常抛出:写访问冲突。这是nullptr。”被抛出。请帮我!!告诉我是否还有其他需要提供的东西。
Buffer.h
#pragma once
#ifndef BUFFER_H
#define BUFFER_H
class Buffer {
private:
int bufferSize = 192 * 2; // one frame takes 2 Byte [int16]
int nBuffers = 4;
int *buffer_ = nullptr;
int* writerPointer = nullptr;
int* listenerPointer = nullptr;
int writerCounter = 0;
int listenerCounter = 0;
int* tempW = nullptr;
int* tempL = nullptr;
public:
Buffer();
~Buffer();
int* getWriterPointer();
int* getlistenerPointer();
int * getPointer();
};
#endif // !BUFFER_H
Buffer.cpp
#include"Buffer.h"
#include <iostream>
Buffer::Buffer() {
buffer_ = reinterpret_cast<int*>(malloc(bufferSize*nBuffers));
memset(buffer_, (int)5, bufferSize*nBuffers);
std::cout << "new Buffer" << bufferSize * nBuffers << std::endl;
listenerPointer = buffer_;
writerPointer = buffer_;
std::cout << "HERE " << *buffer_ << std::endl;
std::cout << "new Buffer" << bufferSize * nBuffers << " pointer a " << listenerPointer << " pointer b " << writerPointer << std::endl;
}
Buffer::~Buffer() {
delete buffer_;
}
...
//For teting purposes
int* Buffer::getPointer(){
bufferSize = 192 * 2;
std::cout << "get pointer asdfasdf::" << writerCounter << std::endl;
std::cout << "pointer's position offset: " << writerCounter - 1 << std::endl;
if (writerCounter == nBuffers - 1) {
writerCounter = 0;
return writerPointer + (bufferSize*(nBuffers - 1));
}
else {
writerCounter += 1;
return writerPointer + (bufferSize*(writerCounter - 1));
}
}
main.cpp
#include <iostream>
#include "Buffer.h"
int main()
{
std::cout << "Hello World!\n";
Buffer *buffer_ = new Buffer();
buffer_->getPointer();
}
答案 0 :(得分:0)
查找协议部分的“零复制”。
您遇到的问题是,在您尝试使用它时,指针实际上是一个nullptr。您需要检查来自malloc
的退货:
buffer_ = reinterpret_cast<int*>(malloc(bufferSize*nBuffers))
if(buffer_) ...
但是,将buffer_ = reinterpret_cast<int*>(malloc(bufferSize*nBuffers));
更改为buffer_ = new int[bufferSize*nBuffers];
,对于每个malloc
,您需要一个free
。对于每一个new
,您都需要一个delete
-请勿混用。
此外,malloc
分配字节,但是int通常为4或8个字节,因此您需要将大小乘以sizeof(int)
以获得正确的大小。忘记malloc
和free
并使用new
和delete
。
这是删除数组的方法:
Buffer::~Buffer() {
delete[] buffer_; // delete array
}