更多封送问题:-( [英] More marshaling woes :-(

查看:59
本文介绍了更多封送问题:-(的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是来自 MSDN 的C代码 [ ^ ]:

typedef struct { <br />    DWORD dwDeltaTime; <br />    DWORD dwStreamID; <br />    DWORD dwEvent; <br />    DWORD dwParms[]; // this is the problem!<br />} MIDIEVENT;

问题dwParms字段是数组.

如果我只想要一个值,没问题-我只是这样声明结构:

The problem is with the array as the dwParms field.

If I just want one value, no problem - I just declare the struct like this:

[StructLayout(LayoutKind.Sequential)]<br />public struct MIDIEVENT<br />{<br />    public int dwDeltaTime;<br />    private int dwStreamID;<br />    public uint dwEvent;<br />    public uint dwParms;<br />}

...,它可以正常工作,但是当我需要时我无法使其数组工作.如果我将最后一个C#字段更改为

... and it works fine, but when I need an array of uints I can''t make it work. If I change the last C# field to

[MarshalAs(UnmanagedType.ByValArray)]<br />public uint[] dwParms;

,则它可以正常工作,但仅获取第一个元素.如果指定SizeConst,则可以很好地获得所有值,但无法知道在编译时将有多少个元素.

帮助!

then it works fine but only gets the first element. If I specify a SizeConst then I can get all the values fine, but I have no way of knowing how many elements there will be at compile time.

Help!

推荐答案

DaveyM69写道:
DaveyM69 wrote:

[MarshalAs(UnmanagedType .ByValArray)]
public uint [] dwParms;

[MarshalAs(UnmanagedType.ByValArray)]
public uint[] dwParms;



您应为MarshalAsAttribute指定 SizeConst 参数.如果不这样做,则应将有问题的字段声明为IntPtr. ``不知道数组的大小,这几天前我也把它写到了线程中.当您获得指向结构的指针时,请使用Marchal.Copy将数据复制到托管数组中.请参阅



You should specify SizeConst parameter for MarshalAsAttribute.You should declare your problematic field as IntPtr,if you don''t know the array size.This I wrote this too into your thread before few days.When you get pointer to your struct use Marchal.Copy to copy the data to managed array.See this sample.


戴夫,

抱歉. [笑]

我还没有使用可变长度数组来做到这一点,我对ByValArray具有固定长度和SizeConst有一定的经验.

您总是可以做的就是忘记struct,只需分配一个具有正确元素计数的实际数组(int或uint,无论哪种方法最适合)即可包含三个个体和嵌入式数组.
然后使用GCHandle对其进行固定并获取其IntPtr并进行传递.这是始终有效的方式,并且永远不会复制任何数据.顺便说一句:完成后不要忘记释放GCHandle.

我希望本机端能够以某种方式找出嵌入式数组的长度,而不是在其外部进行读写.

:)

Hi Dave,

sorry for the delay. [laugh]

I haven''t done this with a variable length array, I have some experience with ByValArray for fixed lengths, with SizeConst.

What you always can do is forget about the struct, just allocate an actual array (either int or uint, whatever suits best) with the right element count to contain the three individuals and the embedded array.
Then use GCHandle to pin it and get its IntPtr, and pass that. That is the way that always works, and never copies any data. BTW: don''t forget to free the GCHandle when done.

I hope the native side will somehow figure out the length of the embedded array, and not read/write outside it.

:)


也许C ++/CLI是一个选择吗?
Maybe C++/CLI is an option?


这篇关于更多封送问题:-(的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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