简体   繁体   中英

Moving structure data in C#

Lets say I have the following structure in C

typedef struct
{
    int field1;
    char field2[16];
} MYSTRUCT;

Now I have a C routine that is called with a pointer to MYSTRUCT and I need to populate the structure, eg,

int MyCall(MYSTRUCT *ms)
{
    char *hello = "hello world";
    int hlen = strlen(hello);
    ms->field1 = hlen;
    strcpy_s(ms->field2,16,hello);
    return(hlen);
}

How would I write MyCall in C#? I have tried this in Visual Studio 2010:

...
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
public struct MYSTRUCT
{
    [FieldOffset(0)]
    UInt32 field1;
    [FieldOffset(4)]
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    string field2;
}

public int MyProc(ref MYSTRUCT ms)
{
    string hello = "hello world";
    int hlen = hello.Length;
    Marshal.Copy(hello, ms.field2, 0, hlen); // doesn't work
    Array.Copy(hello, ms.field2, hlen);      // doesn't work
    // tried a number of other ways with no luck
    // ms.field2 is not a resolved reference
    return(hlen);
}

Thanks for any tips on the right way to do this.

Try changing the StructLayout.

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct MYSTRUCT
{
    public UInt32 field1;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    public string field2;
}

Since, you're passing as a reference, have you tried setting it as:

public int MyProc(ref MYSTRUCT ms)
{
    string hello = "hello world";
    ms.field2 = hello;
    return hello.Length;
}

When using the ref keyword, you'll call MyProc like so:

static void Main(string[] args)
{
    var s = new MYSTRUCT();
    Console.WriteLine(MyProc(ref s)); // you must use "ref" when passing an argument
    Console.WriteLine(s.field2);
    Console.ReadKey();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM