المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : 2D Array Managed and Unmanaged code Data Marshling



C# Programming
05-22-2013, 01:21 PM
Hello Friends,
Thanks in Advance... I am using VS2012 ON WIN7 as my development tool.

I want to get data from C++ into my C# 2D arrays, Arrays are member of strucutre.
I am getting data fine in case of Single dimension arrays and basic data types.

Below is the sample code:-

I have a C# strcuture having 3-4, multidimensional array example.

[StructLayout(LayoutKind.Sequential)]
public struct CompMultiArray
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2 * 200)]
public int [,] tempVacData;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2 * 200)]
public int [,] tempFuncData;
};

Public void GetDataFromUnmanagedCode()
{
CompMultiArray cmpGetData = new CompMultiArray();
cmpGetData .tempVacData = new int[2, 200]; // Allocating or not allocating has no effect
cmpGetData .tempFuncData= new int[2, 200]; // Allocating or not allocating has no effect

CPPClass.FillData(ref cmpGetData);

}

C++ side
struct CompMultiArray
{
int tempVacData[2][200];
int tempFuncData[2][200];
};

void FillData(CompMultiArray& cmData)
{
for(int i =0; i< 2; ++i)
{
for(int j = 0; j < 200; ++j)
{
cmData.tempVacData[i][j] = 100;
cmData.tempFuncData[i][j] = 200;

}
}
}

If I see data in C# side after getting from unmanaged code in Windows->Memory (VS2012), I can see correct data in memory. GC Code to get memory address
GCHandle gch = GCHandle.Alloc(cmpGetData.tempVacData, GCHandleType.Pinned);
// Get a pointer to the array data...
IntPtr pArrayData = gch.AddrOfPinnedObject();
// Via the debugger's memory viewer, confirm
// that the data is laid in memory in sequence.
gch.Free();


But using indexing, i cannot get any data.
for(int i = 0; i < 2; ++i)
{
for(int j = 0; j < 200; ++j)
{
cmpGetData.tempVacData[i,j];
cmpGetData.tempFuncData[i,j]
}
}

please ignore, Dllimport etc. all things are working fine.
please guide me.

Thanks,
Subhash