Pass string and int array in struct into pure C program

Cycler 21 Reputation points
2021-09-20T23:29:50.143+00:00

Hi, guys! I am working on Linux x64 distro.
Code of library lib.c:

include [string.h]

struct Structure
{
int m[2];
char s[6];
} ;

void entry(struct Structure* x);

void entry(struct Structure* x)
{
x->m[1]=10;
strncpy(x->s,"abcde\0",6);
}

void main()
{
}

Code in C#:

using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Structure
{
[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);

C build command:

gcc -o lib -s -shared lib.c

C# call:

var parameter = new Structure { m = new int[] { 5, 7 } , s = "UTF-1\0" } ;
entry(ref parameter);

After execution I had m={5,7} and some garbage in s but I want to rewrite them. How to make call correctly? Thank you.

Developer technologies C#
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.