Create C# structure for CvMat.data union or any way to access it in C#
I need to access 'data' property EmguCV MCvMat structure. But that property is a pointer(IntPtr). I found that structure for this property(data) is an union. It's like this:
union Data
{
char* ptr; // Data pointer for an unsigned char matrix
short* s; // Data pointer for a short matrix
int* i; // Data pointer for an integer matrix
float* fl; // Data pointer for a float matrix
double* db; // Data pointer for a double matrix
} Data;
I tried 开发者_StackOverflow中文版to create a structure for this in C#:
[StructLayout(LayoutKind.Explicit)]
struct MCvMatData
{
[FieldOffset(0)]
public char[] ptr; // Data pointer for an unsigned char matrix
[FieldOffset(0)]
public short[] s; // Data pointer for a short matrix
[FieldOffset(0)]
public int[] i; // Data pointer for an integer matrix
[FieldOffset(0)]
public float[] fl; // Data pointer for a float matrix
[FieldOffset(0)]
public double[] db; // Data pointer for a double matrix
}
And then convert it using Marshel,
MCvMat mat = (MCvMat)Marshal.PtrToStructure(pMat, typeof(MCvMat));
MCvMatData matdata = (MCvMatData)Marshal.PtrToStructure(mat.data, typeof(MCvMatData));
But this gives me an exception. What I need to do is:
- Create data structure in C# for access this pointer or
- Any other way to access MCvMat.data property
I've published a Visual Studio 2010 solution on SkyDrive. It dmonstrates un-marshalling such a structure.
I'll try the MarshalAs attribute when I have more time. Usually, in such situations, I would implement an adapter layer in C++ to make it easier to transfer data between unmanaged and managed code.
精彩评论