C# 在C语言中移动结构数据#

C# 在C语言中移动结构数据#,c#,windows,visual-studio-2010,C#,Windows,Visual Studio 2010,假设我在C中有以下结构 typedef struct { int field1; char field2[16]; } MYSTRUCT; 现在我有一个用指向MYSTRUCT的指针调用的C例程,我需要填充该结构,例如 int MyCall(MYSTRUCT *ms) { char *hello = "hello world"; int hlen = strlen(hello); ms->field1 = hlen; strcpy_s(ms-

假设我在C中有以下结构

typedef struct
{
    int field1;
    char field2[16];
} MYSTRUCT;
现在我有一个用指向MYSTRUCT的指针调用的C例程,我需要填充该结构,例如

int MyCall(MYSTRUCT *ms)
{
    char *hello = "hello world";
    int hlen = strlen(hello);
    ms->field1 = hlen;
    strcpy_s(ms->field2,16,hello);
    return(hlen);
}
我该如何用C#写我的电话?我曾在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);
}

感谢您提供有关正确操作的提示。

尝试更改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();
}

ms.field2=你好,但您可能正在寻找其他内容。显示调用
MyProc
的代码可能很有用……我还注意到C中的结构是int类型而不是unsigned int,因此在C中,如果要将程序移植到C中,您可能需要将数据类型改为Int32而不是uint32,您不必使用结构布局,如果要通过引用传入一个结构,那么最好将其设置为类,因为它是通过引用传入的。然后,您可以根据需要分配值。现在,如果要将函数导出到动态库中,那么使用结构化布局就很好。在C#中使用封送处理或数组复制时,不需要对其执行任何特殊操作。在使用完结构并需要将其发送回非托管方法后,只需将其传递到p/invoked调用中,内置封送将完成所有工作。与从p/调用的方法返回结构相同-.NET将为您完成编组工作,如果您正确定义结构。除非我完全不在这里,您根本不在本机代码之间编组…我假设您正在处理所有编组工作…在这种情况下,就像在C中使用任何其他类一样使用它:)谢谢!尽管我不得不指定“publicstringfield2”,尽管MYSTRUCT是公共的。否则,由于保护级别的原因,它无法访问。我正在靠近它,但它似乎不喜欢“ref MYSTRUCT”。我假设这是在告诉C#它正在接收一个指向结构的指针,对吗?如果不是,那么正确的声明方式是什么?@Neilw,是的,“ref”关键字是指向结构的指针。你怎么称呼我的教授?你有什么错误吗?