Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass char** by reference from c# to unmanaged C++

Tags:

c++

c#

pinvoke

This is the C# code.

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);
    }
}

The unmanaged method is this.

BOOL WINAPI CAM_EnumCameraEx(BOOL bSynchronized, char **ppCameraList, long lMaxCamera, long lMaxCharacter);

The method writes to the passed in array of strings. Is there a way to call this method from c# and have the unmanaged code be able to write to the string array?

like image 821
Adam Nester Avatar asked Nov 10 '22 03:11

Adam Nester


1 Answers

This worked thanks Remus Rusanu that link had the answer. All I had todo was decorate with the [In, Out] on the lst parameter.

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);
    }
}
like image 195
Adam Nester Avatar answered Nov 14 '22 21:11

Adam Nester