简体   繁体   中英

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)

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.

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.

I am not an expert here at all, but I happened to be looking at a piece of code (that i don't understand completely mind you) that is doing this same thing.

Here is what they are doing

[DllImport("")]
private static extern short MethodName([In,Out] ref StructureName variable);

and then on the structure they have the following attribute

[StructLayout(LayoutKind.Sequential, Size = #)]
public struct StructureName {}

I think the part you are looking for is the [In,Out] part, and since it's being passed via ref, you should be getting the same data back.

marked as community wiki so people can fix this if wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM