Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How to pass null to a function expecting a ref?

I've got the following function:

public static extern uint FILES_GetMemoryMapping(     [MarshalAs(UnmanagedType.LPStr)] string pPathFile,     out ushort Size,     [MarshalAs(UnmanagedType.LPStr)] string MapName,     out ushort PacketSize,     ref Mapping oMapping,     out byte PagesPerSector); 

Which I would like to call like this:

FILES_GetMemoryMapping(MapFile, out size, MapName,     out PacketSize, null, out PagePerSector); 

Unfortunately, I cannot pass null in a field that requires type ref Mapping and no cast I've tried fixes this.

Any suggestions?

like image 220
Nick Avatar asked Apr 10 '09 01:04

Nick


People also ask

What is C in coding language?

C is a powerful general-purpose programming language. It can be used to develop software like operating systems, databases, compilers, and so on. C programming is an excellent language to learn to program for beginners. Our C tutorials will guide you to learn C programming one step at a time.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What do you mean by C?

" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.


2 Answers

The reason you cannot pass null is because a ref parameter is given special treatment by the C# compiler. Any ref parameter must be a reference that can be passed to the function you are calling. Since you want to pass null the compiler is refusing to allow this since you are not providing a reference that the function is expecting to have.

Your only real option would be to create a local variable, set it to null, and pass that in. The compiler will not allow you to do much more than that.

like image 88
Andrew Hare Avatar answered Oct 03 '22 05:10

Andrew Hare


I'm assuming that Mapping is a structure? If so you can have two versions of the FILES_GetMemoryMapping() prototype with different signatures. For the second overload where you want to pass null, make the parameter an IntPtr and use IntPtr.Zero

public static extern uint FILES_GetMemoryMapping(     [MarshalAs(UnmanagedType.LPStr)] string pPathFile,     out ushort Size,     [MarshalAs(UnmanagedType.LPStr)] string MapName,     out ushort PacketSize,     IntPtr oMapping,     out byte PagesPerSector); 

Call example:

FILES_GetMemoryMapping(MapFile, out size, MapName,    out PacketSize, IntPtr.Zero, out PagePerSector); 

If Mapping is actually a class instead of a structure, just set the value to null before passing it down.

like image 30
JaredPar Avatar answered Oct 03 '22 05:10

JaredPar