简体   繁体   English

我可以将 C/C++ 结构中的数据编组到具有属性的 C# 结构中吗?

[英]Can I marshal data from a C/C++ struct into a C# struct with properties?

I have a C# struct which is used for interfacing with some native code.我有一个 C# 结构,用于与一些本机代码交互。 Let's say it looks like this and there's an entry point in the dll that can be used to retrieve values for this struct:假设它看起来像这样,并且在 dll 中有一个入口点,可用于检索此结构的值:

public struct MyNativeStruct 
{
    public double ExampleField;
}

[DllImport("SomeDll")]
public static extern MyNativeStruct GetMyNativeStruct();

The struct is used to get structured values out of a native dll ie it mirrors a struct in the dll.该结构用于从本机 dll 中获取结构化值,即它反映了 dll 中的结构。 This is all marshalling properly, so I can use the values just fine in my .NET application.这一切都正确编组,所以我可以在我的 .NET 应用程序中使用这些值。

Later on, I've come to a situation where I really need a struct (or object) that has properties rather than fields so what I really want is something that looks more like this:后来,我遇到了一种情况,我真的需要一个具有属性而不是字段的结构(或对象),所以我真正想要的是看起来更像这样的东西:

struct MyNativeStruct 
{
    public double ExampleField { get; set; }
}

Now of course I could just wrap the extern method which gets the struct from the dll and then convert it to an object with properties like this:现在我当然可以包装从 dll 获取结构的extern方法,然后将其转换为具有如下属性的 object:

public sealed class MyNativeClass 
{
    public double ExampleField { get; set; }
}

// Some quick and dirty function to get values from MyNativeStruct.
public static MyNativeClass GetMyNativeClass() 
{
    var nativeStruct = GetMyNativeStruct();
    return new MyNativeClass { ExampleField = nativeStruct.ExampleField };
}

But this means I will have to create 2 types for each native struct that I want to retrieve from the dll so I was hoping that there may be some nice way to just marshal the native struct into a .NET struct with properties instead of fields.但这意味着我必须为我想从 dll 检索的每个本机结构创建 2 种类型,所以我希望可能有一些很好的方法可以将本机结构编组为具有属性而不是字段的 .NET 结构。

I suppose it could also be possible to create the struct with the public fields first which are backed by properties also in the struct.我想也可以先创建具有公共字段的结构,这些字段也由结构中的属性支持。

Anyway, I was wondering if there was some standard, idiomatic or built-in way to marshal native struct types into C# struct types that have properties rather than public fields.无论如何,我想知道是否有一些标准的、惯用的或内置的方法将本机结构类型编组为具有属性而不是公共字段的 C# 结构类型。

For anyone who comes here in future, my solution was to add the properties after the struct fields (as suggested by GSerg, David Heffernan and Simon Mourier in the comments).对于将来来到这里的任何人,我的解决方案是在结构字段之后添加属性(正如 GSerg、David Heffernan 和 Simon Mourier 在评论中所建议的那样)。

So my struct now looks a little something like this:所以我的结构现在看起来有点像这样:

struct MyNativeStruct 
{
    private double ExampleField;
    public double ExampleProperty => ExampleField;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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