如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写

How transferring an image to buffer in c++(dll) and then read/write in buffer in C#?

本文关键字:缓冲区 然后 图像 传输 dll c++      更新时间:2023-10-16

如何将图像传输到c++(dll(中的缓冲区,然后在c#中的缓冲区时读/写并实时返回到c++(.dll(?我正在寻找的过程如下:

1-首先,我从硬盘上读取图像;Mat inputImage=read("/,…./Test.jpg"(;

2-放入缓冲区:

imencode(".jpg",inputImage,inputBuff,paramBuffer(;

3-将表格c++发送到c#???(我不知道(。

4-从缓冲区读取c#???(我不知道(。

5-将通过c++和c#发生的更改写入缓冲区???(我不知道(。

我正在使用Opencv c++。

我真的很感谢你。

您可以在C#中使用System.Runtime.InteropServices来调用外部库中的函数,例如

c++代码

extern "c"
{
__declspec(dllexport) void __cdecl Read(unsigned char*& buffer)
{
//allocate and write to buffer
}
__declspec(dllexport) void __cdecl Write(unsigned char* buffer)
{
//do something with the buffer
}
}

并将其编译为dll

C#代码

using System.Runtime.InteropServices;
class Main
{
[DllImport(DLL_FILE, CallingConvention = CallingConvention.Cdecl)]
private static extern void Read(out IntPtr buffer);
[DllImport(DLL_FILE, CallingConvention = CallingConvention.Cdecl)]
private static extern void Write(byte[] buffer);
public static void ReadFromExtern()
{
IntPtr bufferPtr = IntPtr.Zero;
Read(bufferPtr);
int length = LENGTH;
byte[] buffer = new byte[length];        
Marshal.Copy(bufferPtr, buffer, 0, length);
//do something with buffer
}
public static void WriteToExtern(byte[] buffer)
{
Write(buffer);
//or do something else
}
}

注:

  1. 如果在c++代码中使用动态分配的内存,请记住还要编写一个包装函数来释放它,否则会导致内存泄漏。

  2. __declspec(dllexport)是特定于Windows的,用于将函数导出到dll。

  3. extern "C"是为了避免c++编译器对名称的篡改,如果使用c编译器,则可以省略

  4. 对于字符串传输,在c++中使用char*,在c#中使用System.Text.StringBuilder