question

Cycler-9545 avatar image
0 Votes"
Cycler-9545 asked JackJJun-MSFT commented

Pass string and int array in struct into pure C program

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.



dotnet-csharp
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@Cycler-9545 ,Since your problem is related to C and gcc, they are currently not supported in the Microsoft Q&A forums. I recommend that you could ask the question related to c#,c and gcc in stackoverflow.


0 Votes 0 ·

0 Answers