You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Direct3D11的pData转Buffer时窗口Resize报错问题求助

问题原因与解决方案

核心问题

你的代码中static unsigned char* buffer = new unsigned char[size];使用了static修饰指针,这意味着buffer只会在第一次执行时分配内存。当窗口放大后,width或height增大,计算出的size会比第一次初始化时更大,但buffer的内存空间还是最初的小尺寸,后续执行memcpy_s时会出现内存越界访问,触发0xC0000005访问冲突错误。

修复代码

你需要跟踪buffer的当前容量,每次处理前检查是否足够容纳新的size,不足则重新分配:

int width = frame.width;
int height = frame.height;
int row_pitch = frame.row_pitch;
unsigned char* data = frame.data;

int size = width * height * 4;
int dstRowPitch = width * 4;

// 用静态变量保存buffer和当前容量,避免重复分配
static unsigned char* buffer = nullptr;
static int current_capacity = 0;

// 检查容量是否足够,不足则重新分配
if (buffer == nullptr || current_capacity < size) {
    // 释放旧内存
    delete[] buffer;
    // 分配新内存
    buffer = new unsigned char[size];
    current_capacity = size;
}

std::cout << height << std::endl;
for (int h = 0; h < height; h++) {
    memcpy_s(buffer + h * dstRowPitch, dstRowPitch,
             data + h * row_pitch,
             min(row_pitch, dstRowPitch));
}

额外优化方案

如果你的场景允许,推荐使用std::vector<unsigned char>替代手动内存管理,它会自动处理扩容和内存释放,代码更简洁安全:

int width = frame.width;
int height = frame.height;
int row_pitch = frame.row_pitch;
unsigned char* data = frame.data;

int size = width * height * 4;
int dstRowPitch = width * 4;

// 用vector自动管理内存
static std::vector<unsigned char> buffer;

if (buffer.size() < size) {
    buffer.resize(size);
}

std::cout << height << std::endl;
for (int h = 0; h < height; h++) {
    memcpy_s(buffer.data() + h * dstRowPitch, dstRowPitch,
             data + h * row_pitch,
             min(row_pitch, dstRowPitch));
}

内容的提问来源于stack exchange,提问作者gdrfgdrf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 06:02:13