0

How transferring an image to buffer in c++(dll) and then read/write in buffer in C# and return to c++(dll) in real time? The process I'm looking is in the following :

1- First, I read an image form hard drive; Mat inputImage = read(“/,…./Test.jpg”);

2- Put in the buffer:

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

3- send form c++ to c# ??? (I don’t know).

4- read in c# from buffer ??? (I don’t know).

5- write the changes that happens through c++ and c# in buffer ??? (I don’t know).

I'm using Opencv c++.

I really thank you.

Marya
  • 21
  • 1
  • 5
  • https://stackoverflow.com/questions/778590/calling-c-sharp-code-from-c – jacob Nov 01 '18 at 07:50
  • Basically, you can use a C++/CLI assembly. In that assembly you can copy the unmanged image buffer to the managed counterpart. That managed buffer can be provided in a public managed class to the .NET world, in your case a second C# assembly that checks/manipulates the image buffer etc. C++/CLI is the fastest interop technology. – KBO Nov 01 '18 at 07:53

1 Answers1

0

You can use System.Runtime.InteropServices in C# to call functions in external libraries, for example

c++ code

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
    }
}

and compile it into a dll

C# code

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
    }
}

Note:

  1. If you used dynamically allocated memory in the c++ code, remember to also write a wrapper function to free it, otherwise causing memory leak.

  2. __declspec(dllexport) is Windows specific to export functions to dll(s).

  3. extern "C" is to avoid name mangling by c++ compilers, can be omitted if using c compilers

  4. For string transferring, use char* in c++ and System.Text.StringBuilder in c#

William Lee
  • 337
  • 4
  • 11