将 C++ struct 数组元组化为 C# [英] Marshal C++ struct array into C#

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

问题描述

我在 C++ 中有以下结构:

I have the following struct in C++:

#define MAXCHARS 15

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

还有一个我正在调用的函数,用于获取包含 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(byte[] 数据);

GetData(byte[] data);

但在那种情况下,我将从第一个 LPRData 结构中获取data"字符串,但在它之后没有任何内容,包括来自同一个 LPRData 的prob"数组.

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?

推荐答案

我会尝试在你的结构体声明中添加一些属性

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 不代表变量

*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++ struct 数组元组化为 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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