473,789 Members | 2,781 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 7188
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
17655
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
3522
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
2645
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
2692
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
3846
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
2816
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
2049
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
5069
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
9817
by: hugo.arregui | last post by:
Hi! I have two struts like that: struct { int num; int num2; struct b arrayOfB; } a;
0
9666
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
9511
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10410
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
10200
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
10139
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
9984
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7529
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4093
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.