Thanks. I was thinking of passing a pointer to the unmanaged function and
then in that function let the pointer point to the Byte Array that I'm
interested in, but how do I declare and use the pointer in C# ?
Thanks
Ole
first way alloc memory in C# and pass it to unmanaged dll to fill data
in C#
using System;
using System.Runtime.InteropServices;
[DllImport("native.dll")]
public static extern bool DllFunction(IntPtr data, int len);
void somefunction()
{
int len = 70;
IntPtr ptr = Marshal.AllocHGlobal(len);
DllFunction(ptr, len);
byte[] returnbytes = new byte[len];
Marshal.Copy (returnbytes, 0, ptr, len);
Marshal.FreeHGlobal(ptr);
}
in C/CPP
BOOL DllFunction(PBYTE data, DWORD len)
{
unsigned char* mdata = (unsigned char*)data;
for(int i = 0; i < len; i ++)
{
mdata[i] = 44; // fill the data
}
}
second way: alloc in unmanaged and fill there back to managed copy and free
in unmanaged
in C#
using System;
using System.Runtime.InteropServices;
[DllImport("native.dll")]
public static extern bool DllFunction(ref IntPtr data, ref int len);
[DllImport("native.dll")]
public static extern bool DllFunctionFree(IntPtr data);
void somefunction()
{
int len = 0;
IntPtr ptr = IntPtr.Zero;
byte[] returnbytes = null;
if(DllFunction(ref ptr, ref len))
{
returnbytes = new byte[len];
Marshal.Copy (returnbytes, 0, ptr, len);
DllFunctionFree(ptr);
}
}
in C/CPP
BOOL DllFunction(PBYTE* data, DWORD* len)
{
DWORD mlen = 255;
*len = mlen;
unsigned char* mdata = (unsigned char*)GlobalAlloc(GMEM_FIXED, mlen);
for(int i = 0; i < mlen; i ++)
{
mdata[i] = 44; // fill the data
}
data = (PBYTE)mdata;
if(somethinggonewrongwithfilling)
{
GlobalFree((HGLOBAL)mdata);
return FALSE;
}
return TRUE;
}
void DllFunctionFree(HGLOBAL data)
{
GlobalFree(data);
}
pozdrawiam
Przemek Sulikowski