C# calling C function that returns struct with fixed size char array

后端 未结 3 1604
别那么骄傲
别那么骄傲 2020-12-16 12:24

So, there have been many variants of this question, and after looking at several I still can\'t figure it out.

This is the C code:

typedef struct
{
u         


        
3条回答
  •  我在风中等你
    2020-12-16 13:04

    Another option to JaredPar's is to utilize the C# fixed size buffer feature. This does however require you to turn on the setting to allow unsafe code, but it avoids having 2 structs.

    class Program
    {
        private const int SIZE = 128;
    
        unsafe public struct Frame
        {
            public uint Identifier;
            public fixed byte Name[SIZE];
        }
    
        [DllImport("PinvokeTest2.DLL", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        private static extern Frame GetFrame(int index);
    
        static unsafe string GetNameFromFrame(Frame frame)
        {
            //Option 1: Use if the string in the buffer is always null terminated
            //return Marshal.PtrToStringAnsi(new IntPtr(frame.Name));
    
            //Option 2: Use if the string might not be null terminated for any reason,
            //like if were 128 non-null characters, or the buffer has corrupt data.
    
            return Marshal.PtrToStringAnsi(new IntPtr(frame.Name), SIZE).Split('\0')[0];
        }
    
        static void Main()
        {
            Frame a = GetFrame(0);
            Console.WriteLine(GetNameFromFrame(a));
        }
    }
    

提交回复
热议问题