I want use a C plugin in Unity3d.
Here is the C function which I want to use.
DECODE_EXPORT CMDecoderFrame* DECODE_CALL CMAllocFrame(CMDecoderCtx *ctx);
The CMDecoderOptions is a struct as following.
struct CMDecoderFrame {
int nVertex; // number of vertices
int nVertexBufferSize;
int nUvBufferSize;
float* pVertexBuffer; // pointer to vertex data
float* pUvBuffer; // pointer to uv data
int nIndex; // number of indices
int nIndexBufferSize;
int32_t* pIndexBuffer; // pointer to index data
int iFrame;
int iSegment;
CMDecoderTexture texture;
};
I'm not familiar about C#, so I don't know how to deal with these pointer both the function return value and the pointer in struct.
I try a solution in C# but it doesn't work well.
struct CMDecoderFrame {
public int nVertex; // number of vertices
public int nVertexBufferSize;
public int nUvBufferSize;
public float[] pVertexBuffer; // pointer to vertex data
public float[] pUvBuffer; // pointer to uv data
public int nIndex; // number of indices
public int nIndexBufferSize;
public int[] pIndexBuffer; // pointer to index data
public int iFrame;
public int iSegment;
public CMDecoderTexture texture;
};
[DllImport("DecodePlugin")]
private static extern IntPtr CMAllocFrame(ref CMDecoderCtx ctx);
Calling in C#.
CMDecoderFrame m_frame = new CMDecoderFrame();
IntPtr frame_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CMDecoderFrame)));
frame_ptr = CMAllocFrame(ref ctx);
m_frame = (CMDecoderFrame)Marshal.PtrToStructure(frame_ptr, typeof(CMDecoderFrame));
Marshal.FreeHGlobal(frame_ptr);
Problem: It seems I need to add the [MarshalAs(UnmanagedType.ByValArray, SizeConst = ?)]
to array in the struct. But I don't know the size, actually the C function does it.
Does anyone has a good solution to deal with this case to calling c function with a lot of pointers in Unity?
Thank you very much!