pointer to a char*[]

jdcoburn used Ask the Experts™
hi -- I'm interfacing  to a dll using C# (not written by me) that accepts a pointer argument. i want to transfer an array of bytes (or chars) to a usb device through the dll provided. i can pass the array of pointers and it shows up on the usb monitor correctly. however, i can't set values in the array at runtime. i get a message that says the object is not created ({"Object reference not set to an instance of an object."}).. i've included the relevant code. below. the first part is the extern prototype; the second part is the part of the method that calls it. i get the message regarding 'new' when i single step through the code and try and load an array element with a value.
        public static extern UInt32 USBH_BulkTx(IntPtr hndl, char pipe_id, char*[] pBuf2, UInt32 buf_length, out UInt16 err);
char*[] pTxbuffer = new char*[30];
            *pTxbuffer[0] = 't';  //this line causes the null reference dialog. if i remove it, the code works but no value is sent.
            if (hndl == (IntPtr)0) return;
            xfer_len = USB_API.USBH_BulkTx(hndl, bulk_out, pTxbuffer, (uint)pTxbuffer.Length, out err);

Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
I haven't used pointers in YEARS.

Looks to me like you've correctly created an array that can hold pointers to single chars. Then, rather than assigning the first element a pointer to a char, you're trying to assign a char directly to whatever its pointer points to. Of course, it doesn't point to anything yet.
You probably want to do something like this. Rather than filling an array of pointers to char, you probably want to fill an array of char.

char[] pTxbuffer = new char[30];
pTxbuffer[0] = 't';

Open in new window

Top Expert 2009
Hi jdcoburn,

For an interop question (which this is since you are interfacing managed code to a native DLL) you will get better answers by cross-posting to C or C++ zones. I am not encouraging you to cross-post all C# questions there but ones specifically with interop are appropriate.

For native C calling convention with the should be, you will need to remember to null-terminate the string / char *.

So per dericstone's sample:

  char[] pTxbuffer = new char[30];
  pTxbuffer[0] = 't';

you should also put

  pTxbuffer[1] = '\0';

Otherwise the C function being called will not know where the buffer stops and will cause a memory error or other runtime problem.


I was able to solve this problem. thanks for the various suggestions.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial