Question

I have an unmanaged code with a fixed struct in memory, i need to read and write the struct from the managed side; the application is a real-time application and i cannot afford the struct's marshalling every time i need it, so i think is better to work in an unsafe context(for performance) and directy handle the pointer. If i have this signature:

public static extern IntPtr COLM104_GetGlobalConf();

and my pointer is a RuntimeDescriptor*, can i store directly store the RuntimeDescriptor* as an object's field or i must keep the pointer in an IntPtr and every time i need it i should do:

(RuntimeDescriptor*)pointerField.ToPointer()

and last thing, can i directly change the p/invoke signature with:

public static extern RuntimeDescriptor* COLM104_GetGlobalConf();

Any help will be apreciated.

Was it helpful?

Solution

You can declare an unsafe member of type RuntimeDescriptor*. And you can declare the return value of your p/invoke to be of type RuntimeDescriptor*.

However, it doesn't really gain you any performance over a cast to RuntimeDescriptor*. Certainly with optimisations enabled, the compiler doesn't need to emit any actual code to perform the cast. However, if you are going down the route of using unsafe code then it's cleaner to be all-in. Declaring the member and return type to be RuntimeDescriptor* makes your program easier to read.

FWIW, there's no need for the call ToPointer() in the code in your question. You can write that cast like this:

(RuntimeDescriptor*)pointerField
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top