的P / Invoke从C到C#不知道数组的大小 [英] P/Invoke from C to C# without knowing size of array

查看:135
本文介绍了的P / Invoke从C到C#不知道数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

右键知道我的code我必须声明为这样的结构,解决了这个16,在编译时知道。

Right know in my code I have structure declared as like this, with fixed this 16, know at compile time.

struct CONSOLE_SCREEN_BUFFER_INFOEX
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public int ColorTable[];
}

但我需要的是能够有这样的结构:

but what I need is to be able to have this structure:

struct CONSOLE_SCREEN_BUFFER_INFOEX
{
   int arraySize;
   [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0)]
   public int ColorTable[];
}

得到C函数响应ARRAYSIZE,初始化大小合适ColorTable阵列,响应到ColorTable的投入造成的。

get the arraySize from C function response, initialize ColorTable array with proper size, put result of response into ColorTable.

不知道这是可能的,只是在做调查,现在,任何意见都非常欢迎。

Not sure if it's possible, just doing investigation right now, and any comments are very welcome.

推荐答案

您可以用一些手工编组使用元帅类做到这一点很容易不够。例如:

You can do this easily enough with some manual marshalling using the Marshal class. For example:

[DllImport(@"MyLib.dll")]
private static extern void Foo(IntPtr structPtr);

private static IntPtr StructPtrFromColorTable(int[] colorTable)
{
    int size = sizeof(int) + colorTable.Length*sizeof(int);
    IntPtr structPtr = Marshal.AllocHGlobal(size);
    Marshal.WriteInt32(structPtr, colorTable.Length);
    Marshal.Copy(colorTable, 0, structPtr + sizeof(int), colorTable.Length);
    return structPtr;
}

private static int[] ColorTableFromStructPtr(IntPtr structPtr)
{
    int len = Marshal.ReadInt32(structPtr);
    int[] result = new int[len];
    Marshal.Copy(structPtr + sizeof(int), result, 0, len);
    return result;
}

static void Main(string[] args)
{
    int[] colorTable = new int[] { 1, 2, 3 };
    IntPtr structPtr = StructPtrFromColorTable(colorTable);
    try
    {
        Foo(structPtr);
        colorTable = ColorTableFromStructPtr(structPtr);
    }
    finally
    {
        Marshal.FreeHGlobal(structPtr);
    }
}

这篇关于的P / Invoke从C到C#不知道数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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