gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:03:51 26 4
gpt4 key购买 nike

我有一些想要从线程中播放的声音。程序启动时,我将声音加载到内存中,然后使用Windows函数PlaySound播放声音。这可行,但是当我尝试从线程播放声音时,出现AccessViolationException,“尝试读取或写入 protected 内存”。

有没有一种方法可以将文件加载到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++ - 从导致AccessViolationException的线程访问文件缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29137303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com