[Mono-list] Memory Allocation in unmanaged code

Marcus mathpup@mylinuxisp.com
Mon, 6 Sep 2004 14:57:31 -0500


I do not know what shared library you are invoking, so I haven't been able to 
test this with the actual shared lib. Inside, I wrote a skeleton C lib that 
fills in the structure when called.

If I change the C# declaration of CupsPrinterStruct from a struct to a class, 
it works.


On Friday 03 September 2004 7:10 pm, Jim Fehlig wrote:
> I am having difficulty with a C# wrapper for some unmanaged C code that
> allocates a list.  Unmanaged code snippet:
>    typedef struct CupsPrinterListStruct
>    {
>        char printerUri[1024];
>        char printerCupsUri[1024];
>        char printerName[1024];
>        char printerMakeAndModel[256];
>        struct CupsPrinterListStruct *nextPtr;
>    }CupsPrinterList;
>    int ListLocalPrinters(CupsPrinterList **printerList);
>    int FreeLocalPrinterList(CupsPrinterList *listHead);
>
> Wrapper code:
>    [ StructLayout(LayoutKind.Sequential) ]
>       public struct PrinterList
>       {
>          [ MarshalAs(UnmanagedType.ByValTStr, SizeConst=1024) ]
>          public string printerUri;
>          [ MarshalAs(UnmanagedType.ByValTStr, SizeConst=1024) ]
>          public string printerCupsUri;
>          [ MarshalAs(UnmanagedType.ByValTStr, SizeConst=1024) ]
>          public string printerName;
>          [ MarshalAs(UnmanagedType.ByValTStr, SizeConst=256) ]
>          public string printerMakeModel;
>          public IntPtr nextElement;
>     }
>    public class PrintLibWrapper
>    {
>       [ DllImport(print) ]
>       public static extern int ListLocalPrinters( ref PrinterList pl);
>    }
>
> Usage:
>    PrinterList printers = new PrinterList();
>    printers.nextElement = IntPtr.Zero;
>    int ccode = PrintLibWrapper.ListLocalPrinters(ref printers);
>    Console.WriteLine(printer name = + printers.printerName); //
> printers.printerName is empty
>
> I can successfully call ListLocalPrinters but unable to read even 1
> result let alone iterate through the list.  Seems I need another level
> of indirection (perhaps an IntPtr) when calling
> PrintLibWrapper.ListLocalPrinters().