从导致AccessViolationException的线程访问文件缓冲区
Access File buffer from a Thread Causing AccessViolationException
我有一些wav声音,我想从线程中播放。当程序启动时,我会将声音加载到内存中,并使用Windows功能PlaySound播放。这是有效的,但当我尝试播放线程中的声音时,我会收到AccessViolationException,"试图读取或写入受保护的内存"。
有没有一种方法可以将文件加载到char数组中,然后从单独的线程中读取它?
这是我用来加载声音文件并播放它的代码
// Code to load sound from file into char*.
ifstream ifs(WaveSounds::sounds::StartupMusic, ios::binary | ios::ate);
// The ios::ate flag sets the filestream
// to the end position, so it's already
// ata the end when we call 'tellg()'.
if (&std::ios::ios_base::good)
{
int length = ifs.tellg();
ifs.seekg(0, ifs.beg);
// Load into the Char * , 'n_StartMusic'.
n_StartMusic = new char[length];
ifs.read(n_StartMusic, length);
ifs.close();
}
// Plays sound from thread, causes AccessViolationException.
static void PlaySoundThread()
{
PlaySound((LPWSTR)WaveSounds::n_CurSound, NULL, SND_MEMORY | SND_ASYNC);
}
// Method that sets sound to play and starts thread.
void WaveSounds::Play_Sound(char* sound)
{
n_CurSound = sound;
n_hmod = GetModuleHandle(0);
Thread^ t = gcnew Thread(gcnew ThreadStart(PlaySoundThread));
t->IsBackground = true;
t->Start();
}
如果char*声音通过wave.play_sound(&c)传递到堆栈上的函数中;到线程启动时,c可能已被删除,因此m_nCurSound指向已清除的内存。
要修复此更改,请将m_nCurSound=sound更改为m_nCurSound=new char[255];strcpy(声音,m_nCurSound);
相关文章:
- C ++程序编译错误,找不到/访问文件
- 从文件读取,并循环访问文件以写入数组
- 确实可以提高directory_iterator在Windows上按字母顺序访问文件和文件夹
- 如何在 bash 中使用管道在 c++ 中使用 getenv() 访问文件?
- 循环访问文件的每一行
- 无法从另一个函数访问文件范围变量的内容
- 如何访问文件的二进制数据?
- 如何从NTFS中的$ MFT文件访问文件的每个块的文件指针
- C++ 写入随机访问文件
- 无法从.cpp访问 .h 文件中的私有成员变量
- boost :: filesystem :: verver()无法访问文件,因为另一个过程正在使用该文件
- 如何在 Qt/C++ 中仅将文件路径作为字符串访问文件
- 如何从 JAVA 程序中访问文件中定义的类.DLL方法
- 如何访问 C 文件中C++公共布尔类成员(进行验证)
- 随机访问文件格式,用于分层组织的二进制文件和文本文件
- 连接到 FTP 服务器并访问文件
- 频繁访问文件映射内存
- 'Good'通过条目维护/更新/访问文件的编程形式
- 访问文件中的单个字符效率低下?(C++)
- wxwidgets类访问文件属性