[英]C# interop with CUDA C dll - redux
问了一些有关我正在从事的项目的问题,得到了很好的反馈并取得了一些进展。 这个想法是创建一个应用程序,该应用程序生成由CUDA加速的分形图像。 我正在C#中创建ui,并让DLL承担了重任。
基本上,我在C#中分配一个字节数组,将其传递给dll以填充像素数据,然后使用该字节创建位图并在ui中使用Windows Forms PictureBox显示它。 以前的问题有所帮助-以前曾经使用dll来分配内存,现在在dll和c#之间使用一致的调用约定,但是代码仍然在“ img = new Bitmap(...)”处提供System.ArgumentException
相关代码:
C ++
extern "C" __declspec(dllexport) void __cdecl generateBitmap(void *bitmap)
{
int width = 1920;
int height = 1080;
int *dev_bmp;
gpuErrchk(cudaMalloc((void**)&dev_bmp, (3*width*height*sizeof(int))));
kernel<<<BLOCKS_PER_GRID, THREADS_PER_BLOCK>>>(dev_bmp, width, height);
gpuErrchk(cudaPeekAtLastError());
gpuErrchk(cudaDeviceSynchronize());
gpuErrchk(cudaMemcpy(bitmap, dev_bmp, (width*height*3), cudaMemcpyDeviceToHost));
cudaFree(dev_bmp);
}
C#
public unsafe class NativeMethods
{
[DllImport(@"C:\Users\Bill\Documents\Visual Studio 2012\Projects\FractalMaxUnmanaged\Debug\FractalMaxUnmanaged.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern void generateBitmap(void *bitmap);
public static Bitmap create()
{
byte[] buf = new byte[1920 * 1080 * 3];
fixed (void* pBuffer = buf)
{
generateBitmap(pBuffer);
}
IntPtr unmanagedPtr = Marshal.AllocHGlobal(buf.Length);
Marshal.Copy(buf, 0, unmanagedPtr, buf.Length);
Bitmap img = new Bitmap(1920, 1080, 3, PixelFormat.Format24bppRgb, unmanagedPtr);
Marshal.FreeHGlobal(unmanagedPtr);
return img;
}
}
// ...
private unsafe void mandlebrotButton_Click(object sender, EventArgs e)
{
FractalBox1.Image = (Image)NativeMethods.create();
}
我仍然在做错什么? 据我所知,所有参数都是无效的,但是当我尝试创建位图时,在System.Drawing中收到了无效的参数异常。
我不确定在您的情况下到底会发生什么,因为您没有在异常中指定哪个参数无效。 我看到您的步伐一定不正确。
步幅类型:System.Int32
一个整数,它指定一条扫描线的起点与下一条扫描线之间的字节偏移量。 这通常(但不是必须)是像素格式(例如,每个像素16位为2)的字节数乘以位图的宽度。 传递给此参数的值必须是四的倍数。
因此,您的构造函数应如下所示:
Bitmap img = new Bitmap(1920, 1080, 1920 * 3, PixelFormat.Format24bppRgb, unmanagedPtr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.