Passing Managed ByteArray to Native C++ DLL

Anyone could help regarding passing ByteArray containing image data from axis camera to Native C++ DLL, Both compile OK, but DLL does not write ByteArray data to file?, just wondering if this is the correct way to pass ByteArray's to C++ DLL's here what we got...

[VC++]

typedef void(*img_process)(IntPtr pArray, int nSize);
img_process _img_process;

HINSTANCE hinstDLL = LoadLibrary((LPCWSTR)L"image_process.dll");


// Get current image of axAxisMediaControl1
int theFormat = 0;
Object^ theBuffer = gcnew Object();
__int32 theBufferSize;
this->axAxisMediaControl1->GetCurrentImage(theFormat, theBuffer, theBufferSize);


// Convert picture object to byte array
array<System::Byte> ^_ByteArray = ObjectToByteArray(theBuffer);

// Initialize unmanged memory to hold the array.
int size = Marshal::SizeOf(_ByteArray[0]) * _ByteArray->Length;

IntPtr pnt = Marshal::AllocHGlobal(size);

try
{
	// Copy the array to unmanaged memory.
	Marshal::Copy(_ByteArray, 0, pnt, _ByteArray->Length);

}
finally
{
	_ img_process = (img_process)GetProcAddress(hinstDLL,"img_process");
	_img_process(pnt, _ByteArray->Length);
	Marshal::FreeHGlobal(pnt);
}
[C++ DLL]

void DLL_EXPORT img_process(BYTE * pArray, int nSize)
{
   
	// Save ByteArray to file
            fstream imgData;
            imgData.open("imagedata.jpg", ios::out | ios::app | ios::binary);
            for(int I = 0; i  <  nSize; i++){

               imgData.write(reinterpret_cast<char*>(&pArray[i]),1);

            }
            imgData.close();
 }

If you brute-force convert the bytes to a BYTE[], what happens?

// ByteArrayTest.cpp : main project file.
#include "stdafx.h"
#include <afx.h>
using namespace System;

array<Byte>^ GetBytes(String^ str)
{
   array<Byte>^ arr = gcnew array<Byte>(str->Length);

   for(int i=0; i< arr->Length; i++)
   {
      arr[i] = str[i];
   }

   return arr;
}

void ProcessBytes(BYTE* byt, int iSize)
{
   for(int i =0; i< iSize; i++)
   {
      printf("%c", byt[i]);
   }
}

int main(array<System::String ^> ^args)
{
    String^ strHello = "Hello World";
    array<Byte>^ arr = GetBytes(strHello);
    BYTE* ba = new BYTE(arr->Length);
    int i=0;
    for each(Byte b in arr)
    {
       ba[i++] = b;
    }

    ProcessBytes(ba, arr->Length);
    return 0;
}

@thines01 Hi thanks for your code contribution, it would seem that the strange problems I am experiencing could well be due to the code running in a background worker thread.
After reading some docs apparently some situations are not guaranteed to be thread safe and result in strange behaver and this could be the case and something I need to look into further.

Many thanks...

This article has been dead for over six months. Start a new discussion instead.