首页 > 解决方案 > 使用 CLI 将 C# byte[] 转换为 C++ char*

问题描述

我正在使用 C# 开发一个应用程序,并且必须在 C++ 中使用带有包装 CLI 的图像处理。在这个项目中,我有一个 C# byte[] 需要发送到需要它作为 unsigned char* 的 C++ 应用程序。我找到了一个非常简单的示例项目,但他的项目使用DllImport而不是 CLI。GitHub

我确实在互联网上搜索过,大多数时候我发现有人marschal.copy用来实现这一点,但是当我这样做时,我收到以下错误:Cannot convert from 'System.IntPtr' to 'byte*'.

这是我使用的代码: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*'"
    }
}

命令行界面

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)
{
    ...
}

所以我的问题是,是否可以使用 CLI 将 byte[] 发送到 C++?如果是这样,我该怎么做?

标签: c#c++clr

解决方案


推荐阅读