1

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!

Dobbie
  • 133
  • 1
  • 10
  • Possible duplicate of [How do I marshal a struct that contains a variable-sized array to C#?](https://stackoverflow.com/questions/5902103/how-do-i-marshal-a-struct-that-contains-a-variable-sized-array-to-c) – Tobias Theel Dec 29 '17 at 10:17
  • Looks like a duplicate to me. The accepted answer, and also the other answers of the linked question should do the trick for you :) – Tobias Theel Dec 29 '17 at 10:18
  • In my case the function return value is also a pointer. How to deal with this situation? – Dobbie Jan 02 '18 at 01:51

0 Answers0