在线程中使用directdraw出现COM接口转换错误
C#线程中使用directdraw出现错误下面的代码是我在线程中调用的,编译可以通过,运行时出现COM强制转换错误
但如果把load_map只做为一个函数在主程序中调用,就可以顺利进行。
public struct map_value
{
public int xx;
public int yy;
}
public struct map_image
{
public DirectDrawSurface7 map;
public int x;
public int y;
public int x_num;
public int y_num;
public int sign;
}
public map_image[,] image_buff = new map_image[400,400];
// load_map 在线程中启动
public void load_map(object vmap)
{
string str;
Bitmap bm;
IntPtr hbitmap;
IntPtr hDCSrc;
IntPtr hDCDst;
map_value pmap = (map_value)vmap;
str = "d:\\map\\" + level_buff[num_level].level_num.ToString() + "\\" + pmap.xx.ToString() + "," + pmap.yy.ToString() + ".jpg ";
image_buff[pmap.xx, pmap.yy].map = DirectDraw.CreateSurface(ref Surface3);
/* 运行时的错误提示是:
未处理的“System.InvalidCastException”类型的异常出现在 map.exe 中。
其他信息: 无法将类型为“System.__ComObject”的 COM 对象强制转换为接口类型“DxVBLib.DirectDraw7”。此操作失败的原因是对 IID 为“{9F76FDE7-8E92-11D1-8808-00C04FC2C602}”的接口的 COM 组件调用 QueryInterface 因以下错误而失败: 不支持此接口 (异常来自 HRESULT:0x80004002 (E_NOINTERFACE))。
*/
bm = new Bitmap(str);
hbitmap = bm.GetHbitmap();
hDCSrc = CreateCompatibleDC((IntPtr)null);
SelectObject(hDCSrc, hbitmap);
hDCDst = (IntPtr)image_buff[pmap.xx, pmap.yy].map.GetDC();
BitBlt(hDCDst, 0, 0, map_w, map_h, hDCSrc, 0, 0, SRCCOPY);
image_buff[pmap.xx, pmap.yy].map.ReleaseDC((int)hDCDst);
DeleteDC(hDCSrc);
DeleteDC(hDCDst);
DeleteObject(hbitmap);
bm.Dispose();
}
//主程序中创建线程的部分
for (xx = least_x; xx - j_x < w + level_buff[num_level].least_num_x; xx++)
{
for (yy = least_y; yy - j_y < h + level_buff[num_level].least_num_y; yy++)
{
vmap.xx = xx;
vmap.yy = yy;
Thread thr = new Thread(new ParameterizedThreadStart(load_map));
thr.Start((object)vmap);
//不启动线程只做为函数调用可以顺利执行
//load_map((object)vmap);
if (sign == 0)
{
image_buff[xx, yy].x = (xx - level_buff[num_level].least_num_x - j_x) * 256;
image_buff[xx, yy].y = (yy - level_buff[num_level].least_num_y - j_y) * 256;
}
else
{
image_buff[xx, yy].x = (xx - level_buff[num_level].least_num_x - j_x) * 256 + image_buff[least_x, least_y].x;
image_buff[xx, yy].y = (yy - level_buff[num_level].least_num_y - j_y) * 256 + image_buff[least_x, least_y].y;
}
image_buff[xx, yy].x_num = xx;
image_buff[xx, yy].y_num = yy;
}
}