其实我做你提到使用CUDA(图形过滤器)完全一样。为了能够从托管代码(WinForms)调用C函数,我使用了InteropServices。
假设您在解决方案中有2个项目 - C++库和一些C#项目。
在C声明函数++库我使用下列参数:
extern "C" int __declspec(dllexport) __stdcall cudaCopyInputData
(int n, int w, int h, byte* data)
{
inputBuffer = data;
bufferLength = n;
inputWidth = w;
inputHeight = h;
useFloatBuffer = 0;
binaryBufferValid = 0;
int bufferSize = bufferLength * sizeof(byte);
int floatBufferSize = bufferLength * sizeof(float);
int binaryBufferSize = w * h * sizeof(int);
cudaMalloc((void**)&cudaInputBuffer, bufferSize);
cudaMemcpy(cudaInputBuffer, inputBuffer, bufferSize, cudaMemcpyHostToDevice);
cudaMalloc((void**)&cudaFloatBuffer, floatBufferSize);
cudaMalloc((void**)&cudaBinaryBuffer, binaryBufferSize);
return 0;
}
为了能够使用InteropServices使用它从C#项目,我导入该功能作为一个静态方法:
[DllImport("CUDA Dll.dll", CharSet = CharSet.Ansi, SetLastError = true, CallingConvention = CallingConvention.StdCall)]
public static extern int cudaCopyInputData(int n, int w, int h, IntPtr data);
你然后可以使用托管代码作为标准方法。
为位图数据传递给进口方法,你可以使用这样的事情:
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
然后通过bmpData.Scan0为指针位图数据和其他一些参数,如宽度,高度,步幅或任何你想要弄清楚C函数中的数据格式。在上面的例子中,每个像素将有4个字节(3个字节+ 1个空字节),因此处理它很舒服。
bmp.UnlockBits(bmpData);
使用C++/CLI:
重用从BMP对象,你处理它后只需要调用处理的数据。从C#直接调用,并且没有难看的不安全攻击 – Indy9000