I'm working on an application in C# and have to use image manipulation in C++ with wrapper CLI. In this project, I have a C# byte[] which needs to be sent to the C++ application which needs it as an unsigned char*. I have found a very simple example project, but his project uses DllImport
instead of CLI. GitHub
I did search on the internet and most of the time I find people using marschal.copy
to achieve this, but when I do this I get the following error: Cannot convert from 'System.IntPtr' to 'byte*'
.
This is the code that I use: C#
Image image = Image.FromFile("Image.bmp");
unsafe
{
using (MemoryStream sourceImageStream = new MemoryStream())
{
image.Save(sourceImageStream, System.Drawing.Imaging.ImageFormat.Png);
byte[] sourceImagePixels = sourceImageStream.ToArray();
// Initialize unmanaged memory to hold the array.
int size = Marshal.SizeOf(sourceImagePixels[0]) * sourceImagePixels.Length;
IntPtr pnt = Marshal.AllocHGlobal(size);
try
{
// Copy the array to unmanaged memory.
Marshal.Copy(sourceImagePixels, 0, pnt, sourceImagePixels.Length);
}
finally
{
// Free the unmanaged memory.
Marshal.FreeHGlobal(pnt);
}
ImageManipulationCppWrapperC wrapper = new ImageManipulationCppWrapperC();
wrapper.ConvertToGray(pnt, sourceImagePixels.Length); // pnt gives the error "Cannot convert from 'System.IntPtr' to 'byte*'"
// wrapper.ConvertToGray(sourceImagePixels, sourceImagePixels.Length); sourceImagePixels gives error: "Cannot convert from 'byte[]' to 'byte*'"
}
}
CLI
void ImageManipulationCppWrapperC::ConvertToGray(unsigned char* data, int dataLen)
{
imP->ConvertToGray(data, dataLen);
}
bool ImageManipulationCppWrapperC::ReleaseMemoryFromC(unsigned char* buf)
{
return imP->ReleaseMemoryFromC(buf);
}
C++
void ImageManipulationCpp::ConvertToGray(unsigned char* data, int dataLen)
{
...
}
So my question is, is it possible to send the byte[] to C++ with the use of CLI? and if so how can I do this?