繁体   English   中英

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

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

如何将图像传输到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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM