A
A
askeet2014-09-23 14:33:04
C++ / C#
askeet, 2014-09-23 14:33:04

Export structure containing arrays from C++ to C#?

In general, I encountered something incomprehensible when reading data from a DLL
Structure in a dll

#pragma pack(push,1) 
typedef struct SIGMPGroup{
  int temp;
  char name[50]; //name of group
  int port; 
  char addr[50]; //network address "229."
  //int ttl;          //
  //int loop;         // 0 - no loop back, 1 - loop back
  
  SIGMPGroup():
  temp(0),
  port(0)
  //ttl(-1),
  //loop(0)
  {}
};
#pragma pack(pop)

Export
#include "StreamEth.h"
#include <stdio.h>
#define dll extern "C" __declspec(dllexport)

StreamEth Eth;

dll
void Leave(const SIGMPGroup& data){
   Eth.leave(data);
}

Call from C#
public static SIGMPGroup DTIGMPGroup = new SIGMPGroup { temp = 56, name = "Example",port = 4000 };
       [StructLayout(LayoutKind.Explicit, Pack = 1, CharSet = CharSet.Ansi, Size = 108)]
       public struct SIGMPGroup{
         [FieldOffset(0)] 
         public int temp;
         [ FieldOffset(4), MarshalAs(UnmanagedType.ByValTStr,SizeConst=50)]
         public string name; //name of group
         [FieldOffset(54)]
         public int port;

         [FieldOffset(58), MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)]
         public string addr;

       }
     
        [DllImport(Eth_DLL, CallingConvention = CallingConvention.Cdecl)]
        public static extern void Leave(ref SIGMPGroup data);

       ImportFunctionEth.Leave(ref ImportFunctionEth.DTIGMPGroup);

After calling the function ImportFunctionEth.Leave(ref ImportFunctionEth.DTIGMPGroup); error appears
Could not load type 'SIGMPGroup' from assembly 'ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 58 that is misaligned or overlapped by a field that does not represent an object.
Although if you comment out the code
[FieldOffset(58), MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)]
         public string addr;

Everything works, why is this happening?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AxisPod, 2014-09-23
@AxisPod

And what will sizeof return in C++ for a given structure?

A
askeet, 2014-09-24
@askeet

It turned out that the code would work, the only way

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
        public struct SIGMPGroup
        { 
            public int temp;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)]
            public string name; //name of group
            public int port;
 
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)]
            public string addr;
        }

But in the case of LayoutKind.Explicit , it throws an error with wrong offset 58.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question