从导致AccessViolationException的线程访问文件缓冲区

Access File buffer from a Thread Causing AccessViolationException

本文关键字:访问 文件 缓冲区 线程 AccessViolationException      更新时间:2023-10-16

我有一些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);