通过c#引用char **到非托管C ++

时间:2015-10-12 18:24:48

标签: c# c++ pinvoke

这是C#代码。

using

非托管方法就是这样。

namespace CameraTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] lst = new string[10];
            for (int i = 0; i < 10; i++)
            {
                lst[i] = new string(' ', 33);
            }
            bool sync = true;
            bool ret = CameraCalls.CAM_EnumCameraEx(sync, lst, 10, 33);

        }
    }

    public static class CameraCalls
    {
        [DllImport("CamDriver64.dll")]
        public static extern bool CAM_EnumCameraEx(bool sync,
                                                   [MarshalAs(UnmanagedType.LPArray)]
                                                   string[] lst, 
                                                   long maxCam, 
                                                   long maxChar);
    }
}

该方法写入传入的字符串数组。有没有办法从c#调用此方法并让非托管代码能够写入字符串数组?

1 个答案:

答案 0 :(得分:1)

感谢Remus Rusanu,链接有了答案。我所有的东西都用lst参数上的[In,Out]装饰。

namespace CameraTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int maxCam = 10,
                 maxChar = 33;

            var lst = (new object[maxCam]).Select(o => new string(' ', maxChar)).ToArray();
            bool sync = true;
            bool ret = CameraCalls.CAM_EnumCameraEx(sync, lst, maxCam, maxChar);

        }
    }

    public static class CameraCalls
    {
        [DllImport("CamDriver64.dll")]
        public static extern bool CAM_EnumCameraEx(bool sync,
                                                   [In, Out]
                                                   string[] lst, 
                                                   long maxCam, 
                                                   long maxChar);
    }
}