Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Array returned from c++ dll to C#

I have this in my dll created in c++

extern "C" __declspec(dllexport)
    char*  __stdcall hh()
{
    char a[2];
    a[0]='a';
         a[1]='b';
    return(a);
}

And this is how I am trying to handle code in c#

[DllImport(@"mydll.dll",CharSet = CharSet.Ansi,CallingConvention = CallingConvention.StdCall)]     
       public static extern IntPtr hh();
       static void Main(string[] args)
        {
            IntPtr a = hh();
           //How to proceed here???
        }


    }

Help in proceeding further.

like image 344
pushE Avatar asked Oct 08 '22 03:10

pushE


1 Answers

There is no way to handle such arrays. char a[2] is allocated on the stack in your C++ function and is destroyed as soon as you return from it. You should either pass an array from C# and fill it in the C++ code or allocate array in the heap and provide some means for freeing it.

When you have it correct the handling will depend on how you return the data from C++ code. If it's still IntPtr you could use Marshal.ReadByte methods to read characters from memory and use Encoding methods to convert those bytes into string if necessary.


const int bufferSize = 2; // suppose it's some well-known value.
IntPtr p = ...; // get this pointer somehow.
for (var i = 0; i != bufferSize; ++i)
{
  var b = Marshal.ReadByte(p, i);
  Console.WriteLine(b);
}

like image 72
Konstantin Oznobihin Avatar answered Oct 12 '22 11:10

Konstantin Oznobihin