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!

3
  • Possible duplicate of How do I marshal a struct that contains a variable-sized array to C#? Commented Dec 29, 2017 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 :) Commented Dec 29, 2017 at 10:18
  • In my case the function return value is also a pointer. How to deal with this situation? Commented Jan 2, 2018 at 1:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.