簡體   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