Search code examples
pinvoke

PInvoke of self referential struct from C++


Following is a self referential struct from C++

typedef struct _FCV 
{
  unsigned long    ulID; 
  unsigned long    ulVersion; 
  unsigned long    ulStatus; 
  unsigned long    ulSize; 
  struct _FCV*     pNext; 
} FCV; 

I need to use PInvoke to translate to C# struct, What is the "pNext" i should declare? Thank you.


Solution

  • You have perhaps reached the point where p/invoke is not the best tool for the job. The complexity here may make a C++/CLI layer a more attractive option.

    With p/invoke you'd need to declare the pNext field as IntPtr. Then you'd need to populate one instance of the struct for each item in the linked list. Finally you'd need to walk through the list assigning to pNext. That will require you to pin each struct with GCHandle.Alloc and then get the pinned address with AddrOfPinnedObject. Once the call has been made you then need to destroy all the GCHandle objects to un-pin the structs.

    So it's possible to do, but the code may be rather unwieldy, and may not be particularly efficient. You should seriously consider C++/CLI instead.