Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

p/invoke C function that returns pointer to a struct

How do I declare in C# a C function that returns a pointer to a structure?

I believe following is one way to do that, followed by Marshal.PtrToStructure to get actual structure value.

// C-function
SimpleStruct * Function(void);

// C# import
[DllImport("MyDll.dll")]
public static extern IntPtr Function();
  1. Am I correct about that?
  2. Are there other ways to accomplish the same? (It would be OK to get struct back by value)
like image 744
THX-1138 Avatar asked Feb 28 '23 19:02

THX-1138


2 Answers

Since the function returns a pointer (hopefully not a locally allocated one?) your best bet is to manually marshal it (via Marshal.PtrToStructure).

If it were a parameter you could create a managed version of the structure using the PInvoke Interop Assistant then pass it via ref or out.

like image 67
Shea Avatar answered Mar 03 '23 15:03

Shea


Caveat: this will only work if the pointer returned is to memory already managed by the CLR

I believe what you are looking for is

// C# import
[DllImport("MyDll.dll")]
[return : MarshalAs(UnmanagedType.LPStruct)]
public static extern StructureName Function();

[StructLayout(LayoutKind.Sequential)]
public class StructureName {}

This should eliminate the need for any manual Marshal.PtrToStructure calls. Depending on what your structure contains, you may need to tag some fields with MarshalAs attributes as appropriate. MSDN has a good example of this.

like image 38
Eric Burnett Avatar answered Mar 03 '23 15:03

Eric Burnett