元帅C ++结构数组转换成C# [英] Marshal C++ struct array into C#

查看:133
本文介绍了元帅C ++结构数组转换成C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++下面的结构:

I have the following struct in C++:

#define MAXCHARS 15

typedef struct 
{
    char data[MAXCHARS];
    int prob[MAXCHARS];
} LPRData;

和我是P /调用到一个函数来获取这些结构的3数组:

And a function that I'm p/invoking into to get an array of 3 of these structures:

void GetData(LPRData *data);

在C ++中我只想做这样的事情:

In C++ I would just do something like this:

LPRData *Results;
Results = (LPRData *)malloc(MAXRESULTS*sizeof(LPRData));
GetData( Results );

和它会工作得很好,但在C#中我似乎无法得到它的工作。
我创建了一个C#结构是这样的:

And it would work just fine, but in C# I can't seem to get it to work. I've created a C# struct like this:

public struct LPRData
{

    /// char[15]
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]
    public string data;

    /// int[15]
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)]
    public int[] prob;
}

如果我初始化的那些3(以及所有的子数组)的数组,并把它传递到这一点:

And if I initialize an array of 3 of those (and all their sub-arrays) and pass it into this:

GetData(LPRData[] data);

它返回成功,但LPRData数组中的数据并没有改变。

It returns with success, but the data in the LPRData array has not changed.

我甚至试图建立一个原始字节数组的3 LPRData的大小并传递到一个函数原型是这样的:

I've even tried to create a raw byte array the size of 3 LPRData's and pass that into a function prototype like this:

的GetData(字节[]数据);

GetData(byte[] data);

但在这种情况下,我会从一开始LPRData结构中的数据字符串,但是没有后,包括来自同一LPRData的概率数组。

But in that case I will get the "data" string from the very first LPRData structure, but nothing after it, including the "prob" array from the same LPRData.

如何妥善处理这一任何想法?

Any ideas of how to properly handle this?

推荐答案

我会尝试加入一些属性,你的结构decloration

I would try adding some attributes to your struct decloration

[StructLayout(LayoutKind.Sequential, Size=TotalBytesInStruct),Serializable]
public struct LPRData
{
/// char[15]
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]
public string data;

/// int[15]
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)]
public int[] prob;
}

*注TotalBytesInStruct不旨在重新present可变

*Note TotalBytesInStruct is not intended to represent a variable

JaredPar也是正确的使用IntPtr的类可能是有用的,但它已经相当一段时间,因为我用的PInvoke所以我生锈。

JaredPar is also correct that using the IntPtr class could be helpful, but it has been quite awhile since I have used PInvoke so I'm rusty.

这篇关于元帅C ++结构数组转换成C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆