将C ++二维固定长度char数组作为结构成员 [英] Marshaling a C++ two-dimensional fixed length char array as a structure member

查看:182
本文介绍了将C ++二维固定长度char数组作为结构成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调用一个非托管C ++函数,它有一个结构作为输入参数。
结构在头文件中定义如下:

I am trying to call an unmanaged C++ function, that has a structure as an input parameter. The structure is defined in the header file like this:

struct MyStruct
{
int     siOrder;
char     aaszNames[6][25];
int     siId[6];
int     siTones[6];        
};

我试图声明托管结构如下:

I tried to declare the managed struct as following:

[StructLayoutAttribute(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct MyStruct {

public int siOrder;

[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst=150)]
public string aaszNames;

[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=6, ArraySubType=UnmanagedType.I4)]
public int[] siId;

[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=6, ArraySubType=UnmanagedType.I4)]
public int[] siTones;
}

但没有成功。我猜测编组失败,因为aaszNames实际上是一个数组的六个25长的null终止字符串。
我尝试声明aaszNames为

But without any success. I am guessing that the marshaling fails, since the aaszNames is actually an array of six 25 long null-terminating strings. I tried declaring aaszNames as

 [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=150)]
 public char[] aaszNames;

必要时用空填充数组。但是,没有了。

filling the array with nulls where necessary. But, again, nothing.

有没有什么我缺少?我错了什么?

Is there something I am missing? What am I dong wrong? What is the best way to marshal this 2-D char array?

请提供任何提示。

推荐答案

尝试使用多个C#结构:

Try using multiple C# structs:

[StructLayoutAttribute(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct MyStruct_Name
{
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 25)]
    public string name;
}

[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MyStruct
{
    public int siOrder;

    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6)]
    public MyStruct_Name aaszNames;

    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I4)]
    public int[] siId;

    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I4)]
    public int[] siTones;
}

这是我一直在传递C风格字符串的数组。

This is how I've been passing arrays of C-style strings around.

不要忘记创建aaszNames的内容! marshaller讨厌null引用。

Don't forget to create the contents of aaszNames! The marshaller hates null references.

MyStruct foo = new MyStruct();
for (int i = 0; i < 6; i++)
{
    foo.aaszNames[i] = new MyStruct_Name();
    foo.aaszNames[i].name = "";
}

祝你好运!

这篇关于将C ++二维固定长度char数组作为结构成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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