c# - 使用 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++?如果是这样,我该怎么做?
解决方案
推荐阅读
- react-native - TypeError: _ExponentCameraManager__WEBPACK_IMPORTED_MODULE_13__ .default.requestPermissionsAsync 不是函数
- python - Tensorflow 卡在第一个 epoch
- java - 给定斐波那契数列中的数字总和
- java - Apache Camel 重新交付策略 Junit 测试
- c# - 从键盘键入时创建通用事件处理程序
- python - For循环的列表理解替代代码
- dynamics-crm - CRM 2015 - 如果我从 Project-Product、Quote-Product、Order-Project 中选择多条记录(不是批量删除),删除几乎需要 35 到 40 秒
- tensorflow - 具有不可训练层的张量流
- python - 如何在 Json 对象中转换我的字典?
- python - 连接后如何正确访问单个张量?