pushE
pushE

Reputation: 414

How to know size of an array passed from C++ dll to C#

Actually I am using a C++ dll in C# as follows

MY C++ CODE

extern "C" __declspec(dllexport)
    char**  __stdcall hh()
{
 static char* myArray[3] = {"A1", "BB2", "CC3",};
    return myArray;
}

MY C# CODE

[DllImport(@"ourdll.dll",CharSet = CharSet.Ansi,CallingConvention = CallingConvention.StdCall)]     
      public static extern IntPtr hh();
       static void Main(string[] args)
        {
            IntPtr a = hh();
            int j = 0;
            string[] s=new string[100]; //I want this to be dynamic
           do
           {
               s[j] = Marshal.PtrToStringAnsi(Marshal.ReadIntPtr(a,4*j));
               j++;
           }
           while(s[j-1] != null);
        }

I am unable to get the size of array returned by hh();How can I get the size of array so that my line of code

string[] s=new string[100]; changes to string[] s=new string[ACtual Length of array];

Upvotes: 0

Views: 616

Answers (2)

Raghuveer
Raghuveer

Reputation: 2638

if you want to find the length of the array in PInvoke you can use Marshal.SizeOf(object) method

MSDN Link

It works for me for Structures

Upvotes: 1

drewag
drewag

Reputation: 94723

You are either going to have to return the size of the array as well (possibly a variable by reference) or you can add a NULL terminator to the list. If you use a NULL terminator you can loop through the array until you find NULL in order to determine the size.

Upvotes: 3

Related Questions