473,842 Members | 1,633 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

struct -> null

Hello,

if I have a P/Invoke method: open(STRUCT1 str, STRUCT2 str2);

is there a way to pass <null> for a struct in C#?
How can I solve this?

thx
Nov 15 '05 #1
7 7189
Structs are value types (in C++ and in C#), so NULL would be incompatible
with any struct type. Now, if you want to pass NULL for a reference type,
for example if yourfunction was declared like:

open (struct struct1 *str, struct struct1 *str2) { ... }

you would do so with IntPtr.Zero (that is NULL).

Hope that helps,
-JG
Nov 15 '05 #2
Create two DllImports for the same api. The second one will be overloaded
with something like "object flag" on the STRUCT2 parm. Now you can pass a
STRUCT2 or a null ref. Example:

[DllImport("kern el32.dll")]
public static extern uint GetFileSize(
IntPtr hFile, //[in] Handle to the file for size.
ref uint fileSizeHigh); //[out] Pointer to var where high-order word is
returned.

[DllImport("kern el32.dll")]
public static extern uint GetFileSize(
IntPtr hFile, //[in] Handle to the file for size.
object flag); //[out] Overloaded to allow passing null.

--
William Stacey, MVP

"Dirk Reske" <_F*******@gmx. net> wrote in message
news:u0******** ******@TK2MSFTN GP11.phx.gbl...
Hello,

if I have a P/Invoke method: open(STRUCT1 str, STRUCT2 str2);

is there a way to pass <null> for a struct in C#?
How can I solve this?

thx

Nov 15 '05 #3
From the help on IntPtr.Zero: "The value of this field is not equivalent to
a null reference..."
Wouldn't you be passing a ptr to the IntPtr struct that contains a zero? Or
does pInvoke change this to a null ref?

--
William Stacey, MVP

"Juan Gabriel Del Cid" <jd*****@atrevi do.nospam.net> wrote in message
news:eP******** ******@TK2MSFTN GP10.phx.gbl...
Structs are value types (in C++ and in C#), so NULL would be incompatible
with any struct type. Now, if you want to pass NULL for a reference type,
for example if yourfunction was declared like:

open (struct struct1 *str, struct struct1 *str2) { ... }

you would do so with IntPtr.Zero (that is NULL).

Hope that helps,
-JG

Nov 15 '05 #4
is there a way to pass <null> for a struct in C#?
How can I solve this?


In addition to what the other suggested, another way is to use unsafe
code and a real pointer type

STRUCT1* str

And yet another option is to change the parameter type to an array

STRUCT1[] str

and then either pass in a single-element array or null.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.
Nov 15 '05 #5
> From the help on IntPtr.Zero: "The value of this field is not
equivalent to a null reference..."


Of course it's not a null reference, it's a value type. In the past there
was no distinction between a value type and a reference type. You could cast
data to whatever you wanted and back. For example, a pointer is really
nothing more than an integer (4 bytes on a 32 bit processor). In this case,
NULL is just 4 bytes all set to zero (just like IntPtr.Zero).

So, in C/C++ you have:

if ((int)NULL == 0) {
// this is always true
}

and in C# you have:

if ((int)null == 0) {
// this will never compile because you can't convert
// null (or any other reference type)
// to an int (or any other value type)
}

if ((int)IntPtr.Ze ro == 0) {
// this is always true
}

Hope that clears it up for you,
-JG
Nov 15 '05 #6
I'd bet that the method you're trying to call takes a pointer to a struct,
and you should be using:

open(ref STRUCT1 str, ref STRUCT2 str2);

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://blogs.gotdotnet.com/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
"Dirk Reske" <_F*******@gmx. net> wrote in message
news:u0******** ******@TK2MSFTN GP11.phx.gbl...
Hello,

if I have a P/Invoke method: open(STRUCT1 str, STRUCT2 str2);

is there a way to pass <null> for a struct in C#?
How can I solve this?

thx

Nov 15 '05 #7
In terms of the OP question, IntPtr does not help him. Assume the exported
function is something like:
BOOL DoSomething(SOM ESTRUCT * struct1);

And the managed struct and/or class is:
// Declares a managed structure for the unmanaged structure.
[ StructLayout( LayoutKind.Sequ ential )]
public struct MyStruct
{
public int one = 1;
public long two =2;
}
// Declares a managed class for the unmanaged structure.
[ StructLayout( LayoutKind.Sequ ential )]
public class MyClass
{
public int one = 1;
public long two = 2;
}

Then his exports might be something like (among others):
// Because MyStruct is a value type, you cannot pass null as a
// parameter. Instead, declare an overloaded method.
[ DllImport( "Kernel32.d ll" )]
public static extern bool DoSomething(
ref MyStruct myStruct );

[ DllImport( "Kernel32.d ll" )]
public static extern bool DoSomething(
int flag ); // Declares an int instead of a structure reference so you
can pass a zero.

// Because MyClass is a class, you can also pass null as parameter.
// No overloading is needed.
[ DllImport( "Kernel32.d ll", EntryPoint="DoS omething" )]
public static extern bool DoSomething2(
MyClass myClass );

Then he can call "DoSomethin g" like:
MyStruct ms;
MyClass mc = new MyClass();
bool b = DoSomething(ref ms); //Call using ref to struct.
bool b = DoSomething(0); //Call passing zero. You could pass
(int)IntPtr.Zer o here, but why?
bool b = DoSomething2(mc ); //Call using ref to class.
bool b = DoSomething2(nu ll); //Call passing null.

In none of those cases does IntPtr help.

--
William Stacey

"Juan Gabriel Del Cid" <jd*****@atrevi do.nospam.net> wrote in message
news:uV******** ******@TK2MSFTN GP12.phx.gbl...
Hope that clears it up for you,

Nov 15 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
17677
by: Roy Hills | last post by:
When I'm reading from or writing to a network socket, I want to use a struct to represent the structured data, but must use an unsigned char buffer for the call to sendto() or recvfrom(). I have two questions: 1. Is it generally safe to "overlay" the structure on the buffer, e.g.: unsigned char buffer;
10
3524
by: Rick Anderson | last post by:
All, I am receiving the following compilation error on LINUX (but not Solaris, HPUX, WIN32, etc): compiling osr.c LBFO.h(369): warning #64: declaration does not declare anything extern struct foobar; ^
19
2653
by: Russell Shaw | last post by:
Hi, I have two structs in a header file, and they reference each other, causing a compile error. Is there a standard way to deal with this? typedef struct { ... RtAction *actions; } RtWidget;
6
2697
by: S.Tobias | last post by:
I'm trying to understand how structure type completion works. # A structure or union type of unknown # content (as described in 6.7.2.3) is an incomplete type. It # is completed, for all declarations of that type, by ^^^ # declaring the same structure or union tag with its defining # content later in the same scope. ^^^^^ (6.2.5#23)
16
3849
by: burn | last post by:
Hello, i am writing a program under linux in c and compile my code with make and gcc. Now i have 4 files: init.c/h and packets.c/h. Each header-file contains some: init.h: struct xyz {
4
2821
by: PCHOME | last post by:
Hi! I have questions about qsort( ). Is anyone be willing to help? I use the following struct: struct Struct_A{ double value; ... } *AA, **pAA;
15
2052
by: dutchgoldtony | last post by:
Hi all, I was just wondering if this is possible. I'm trying to implement a viterbi decoder in C and am creating an array of nodes (the struct), and an array of pointers to nodes (the member I'm worried about) connecting to it like so: // snippet start typedef struct _node{ char state; // The state of each node ("00","01","10","11")
7
2262
by: Alex | last post by:
If I have two struct. See below: struct s1 { int type; int (*destroy)(struct s1* p); } struct s2 { struct s1 base;
4
5076
by: hobbes992 | last post by:
Howdy folks, I've been working on a c project, compiling using gcc, and I've reached a problem. The assignment requires creation of a two-level directory file system. No files have to be added or deleted, however it must be initialized by a function during run-time to contain so many users which each contain so many directories of which each contain so many files. I've completed the program and have it running flawlessly without implementing...
4
9818
by: hugo.arregui | last post by:
Hi! I have two struts like that: struct { int num; int num2; struct b arrayOfB; } a;
0
9872
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10945
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10612
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10672
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7038
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5696
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5885
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4089
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3145
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.