After the comments of the colleagues, the public answer is complete. The code was checked in Linux x64 and NET 5.
Simplified library team:gcc -o lib -s -shared lib.cOPTION 1Code lib.c#include <string.h>
struct Structure
{
int a;
char c;
double d;
float f;
int m[2];
char s[6];
};
void entry(struct Structure* x);
void entry(struct Structure* x)
{
memcpy(x->m, (int[2]){1, 2}, sizeof x->m);
strncpy(x->s,"abcde\0",6);
}
void main()
{
}
C#[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Structure
{
public int a;
public char c;
public double d;
public float f;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.I4, SizeConst = 2)]
public int[] m;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
public string s;
}
[DllImport("lib")]
public static extern void entry([MarshalAs(UnmanagedType.Struct), In, Out] ref Structure s);
Call code C#var parameter = new Structure { a = 1, c = 'c', f = 2, d = 3, m = new int[] { 5, 7 } , s = "UTF-1\0" };
entry(ref parameter);
OPTION 2Code lib.c#include <uchar.h>
#include <string.h>
struct Structure
{
int a;
char c;
double d;
float f;
int m[2];
char16_t s[6];
};
struct Structure entry(struct Structure x);
struct Structure entry(struct Structure x)
{
char16_t string[6] = u"abcdef";
memcpy(x.s, string, sizeof(string));
return x;
}
void main()
{
}
C# [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct Structure
{
public int a;
public char c;
public double d;
public float f;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.I4, SizeConst = 2)]
public int[] m;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
public string s;
}
[DllImport("lib")]
[return: MarshalAs(UnmanagedType.Struct)]
public static extern Structure entry([MarshalAs(UnmanagedType.Struct), In] Structure s);
Call code C#Structure structure = entry(new Structure { a = 1, c = 'c', f = 2, d = 3, m = new int[2] { 5, 7 }, s = "UTF-16" });
I wonder if the shorter length of the program on C can be returned, and more than SizeConst, it won't work, it will be cut.