Using P/Invoke to call a pointer to a pointer

H

harter.jim

I am currently calling a 3rd party external library using P/Invoke.
The library gives me a handful of functions that I need to call. I
have been successful at calling many of them, but I am some trouble
calling a certain function that requires a pointer to a pointer. Here
is the relevant header information:

typedef struct _ITEM_INFO
{
int itemID;
int itemValue;
} ITEM_INFO;

typedef struct _ITEMS
{
int count; /* number of items */
ITEM_INFO * itemList; /* list of iteminfo */
} ITEMS;

RESULT_CODE WINAPI GetItemList(ITEMS ** itemList);

I need a way to call the GetItemList. In the end, I need the list of
itemIDs and their associated values. I found an article on a technique
for calling a pointer to a pointer to a struct at
http://www.vsj.co.uk/articles/display.asp?id=501. That technique used
the Marshal.AllocHGlobal and Marshal.StructureToPtr methods, but the
Marshal.AllocHGlobal requires a size parameter for the ITEMS structure.
However, this structure does not have a constant size due to the list
inside of it. Does anyone know how I might be able to call this
function from C#?

Thanks for your help.

Jim
 
M

Mattias Sjögren

I need a way to call the GetItemList. In the end, I need the list of
itemIDs and their associated values. I found an article on a technique
for calling a pointer to a pointer to a struct at
http://www.vsj.co.uk/articles/display.asp?id=501. That technique used
the Marshal.AllocHGlobal and Marshal.StructureToPtr methods, but the
Marshal.AllocHGlobal requires a size parameter for the ITEMS structure.

Are you sure you have to allocate the memory? From the signature it
looks like the caller allocates and returns a pointer through the only
parameter. In that case, just type it as out IntPtr on the C# side.

However, this structure does not have a constant size due to the list
inside of it.

The struct itself still has a constant size (sizeof(int) +
sizeof(ITEM_INFO*)).


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top