在c#中移动结构数据

本文关键字:结构 数据 移动 | 更新日期: 2023-09-27 18:11:49

假设我在C中有如下结构

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

现在我有一个C例程,它是用指向MYSTRUCT的指针调用的,我需要填充结构,例如

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

如何在c#中编写MyCall ?我在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);
}

在c#中移动结构数据

尝试改变StructLayout。

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

既然你是作为引用传递的,你有没有试过将其设置为:

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

使用ref关键字时,您将像这样调用MyProc:

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();
}