"using namespace" in header files in C++/CLI applications - c#

I know in general, you should never put something like "using namespace std;" in a c++ header, since it will propagate to any file that includes that header.
I'm wondering if this rule of thumb also applies to .NET namespaces in a C++/CLI program. I'm writing a wrapper for a c++ library, to be used in C#. The idea of "using namespace _____" in the CLI headers seems appealing because these namespaces go quite deep. Having "System::Collections::Generic::List" in front of every list in my function prototypes, for example, feels unnecessarily verbose and kills readability.
I think that this might be okay, because (and I'm not positive on this point, I could be wrong) I don't believe "using System::Collections::Generic" propogates across C# files the way it does in C++ headers. I don't expect it to negatively impact anyone using my CLI library in a C# project.
I couldn't really find any information on what the proper custom is in CLI-world if there is one, or if I'm wrong about the downsides - so I appreciate any advice!

Related

Why is "using System;" not considered bad practice?

I have a C++ background and I do fully understand and agree with the answers to this question: Why is “using namespace std;” considered bad practice?
So I'm astonished that, having some experience with C# now, I see the exact opposite there:
using Some.Namespace; is literally used everywhere. Whenever you start using a type, you add a using directive for its namespace first (if it isn't there already). I cannot recall having seen a .cs-file that didn't start with using System; using System.Collections.Generic; using X.Y.Z; etc....
In fact, if you add a new file via the Visual Studio wizard, it automatically adds some using directives there, even though you may not need them at all. So, while in the C++ community you get basically lynched, C# even encourages doing this. At least this is how it appears to me.
Now, I do understand that using directives in C# and C++ are not exactly the same thing. Also, I do understand that one of the nastiest things you can do with using namespace in C++, namely putting it in a header file, has no equivalently nasty counterpart in C# due to the lack of a concept of header files and #include.
However, despite their differences, using directives in C# and C++ serve the same purpose, which is only having to type SomeType all the time, rather than the much longer Some.Namespace.SomeType (in C++ with :: instead of .). And with this same purpose, also the danger appears to be the same to me: naming collisions.
In the best case this results in a compilation error, so you "only" have to fix it. In the worst case, it still compiles and the code silently does different things than you intended it to do. So my question is: Why (apparently) are using directives considered so unequally bad in C# and C++?
Some ideas of an answer that I have (none of these really satisfy me, though):
Namespaces tend to be much longer and much more nested in C# than in C++ (std vs. System.Collection.Generic). So, there is more desire and more gain in de-noising the code this way. But even if this is true, this argument only applies when we look at the standard namespaces. Custom ones can have any short name you like, in both C# and C++.
Namespaces appear to be much more "fine granular" in C# than in C++. As an example, in C++ the entire standard library is contained in std (plus some tiny nested namespaces like chrono) while in C# you have System.IO, System.Threading, System.Text etc. So, the risk of having naming collisions is smaller. However, this is only a gut feeling. I didn't actually count how many names you "import" with using namespace std and using System. And again, even if this is true, this argument applies only when looking at the standard namespaces. Your own ones can be designed as fine granular as you wish, in both C# and C++.
Are there more arguments? I'm especially interested in actual hard facts (if there are any) and not so much in opinions.
Why is “using System;” not considered bad practice?
"using System;" is not universally not considered a bad practice. See for example: Why would you not use the 'using' directive in C#?
But it may be true that it is not considered quite as bad as using namespace std. Probably because:
C# does not have header files. It is uncommon to "include" one C# source file into another using a pre-processor.
std namespace is nearly flat i.e. almost all standard library functions, types and variables are in it (there are few exceptions such as the filesystem sub-namespace). It contains very, very high number of identifiers. To my understanding, System contains much fewer names, and instead has more sub-namespaces.
In C#, there are no global functions or variables. As such, the number of global identifiers is typically quite small in contrast to C++ which does have those: Furthermore, it is typical to use C libraries (often indirectly) which doesn't have namespaces, and therefore place all their names into the global namespace.
As far as I know, C# has no argument dependent lookup. ADL in conjunction with name hiding, overloading etc. can produce cases where some programs are not affected by a name conflict, while others are subtly affected, and catching all corner cases is not feasible with testing.
Because of these differences, “using System;” has lower chance of name conflict than using namespace std.
Also, namespace "importing" is in a way, a self-perpetuating convention: If it is conventional to import a standard namespace, then programmers will conventionally try to avoid choosing names from that namespace for their own identifiers, which helps to reduce problems with such convention.
If such an import is considered a bad practice, then programmers will be less likely to even attempt such avoidance of conflicts with imported namespaces. As such, conventions tend to get polarised either for or against the practice, even if weights of arguments between the choices were originally subtle.
However, despite their differences, using directives in C# and C++ serve the same purpose, which is only having to type SomeType all the time, rather than the much longer Some.Namespace.SomeType (in C++ with :: instead of .). And with this same purpose, also the danger appears to be theto me: naming collisions.
Yes, but you didn't export that danger (read: forcing others to deal with it), because of:
Now, I do understand that using directives in C# and C++ are not exactly the same thing. Also, I do understand that one of the most nasty things you can do with using namespace in C++, namely putting it in a header file, has no equivalent in C# due to the lack of a concept of header files and #include.
So it's rather a different category of thing.
Also, C++ is not "designed" to be developed in an IDE the same way C# is. C# is basically always written in Visual Studio with its Intellisense and whatnot. It's designed to be used that way, by the people who created it. Regardless of how many people use an IDE to develop in C++, it is not designed with that use case as an overwhelming concern.
Namespaces appear to be much more "fine granular" in C# than in C++.
Yes, that too. using namespace std and using System.Collection.Generic are incomparable.
So don't compare them!

Moving to a DLL

I've been tasked with moving the more useful parts of my code into a dll (if possible) for ip protection and to stop other developers changing parts that don't need to be changed.. I'm curious on how best to handle the namespaces and method parameters that relate to classes that I have created..
Is it just as simple as making sure they are in the same namespace? I get the feeling this will cause problems for others when the dll is to be used in other applications..
The only other viable solution I can see coming forward is to move my class variables into this new dll and then use them under this namespace..
If its needed im using winforms
I don't see how moving the code to a dll will protect your IP better.
That being said, my suggestion is just to copy the code to minimize the amount of the client code which needs to be rewritten. You will more likely need to change some classes from internal to public, or at least some methods visibility.
There is no reason that keeping the same namespaces will cause troubles for using the dll in other apps if your namespaces are even moderately sensible. In worst case, you can alias the namespaces/class names (with using directive) in the client apps to solve the issues if there are any.

Parse .h header files into c# data structures in runtime

I'm trying to write a C# library to manipulate my C/C++ header files.. I want to be able to read and parse the headers file and manipulate function prototypes and data structures in C#. I'm trying to avoid writing a C Parser, due to all code brances caused by #ifdefs and stuff like that.
I've tryed playing around with EnvDTE, but couldn't find any decent documentation.
Any ideas how can I do it?
Edit -
Thank you for the answers... Here are some more details about my project: I'm writing a ptrace-like tool for windows using the debugging API's, which enable me to trace my already compiled binaries and see which windows API's are being called. I also want to see which parameter is given in each call and what return values are given, so I need to know the definition of the API's. I also want to know the defition for my own libraries (hence, the header parsing approach). I thought of 3 solutions:
* Parsing the header files
* Parsing the PDB files (I wrote a prototype using DIA SDK, but unfortionatly, the symbols PDB contained only general info about the API's and not the real prototypes with the parameters and return values)
* Crawling over the MSDN online library (automaticly or manualy)
Is there any better way for getting the names and types for windows API's and my libraries in runtime in c#?
Parsing C (even "just" headers) is hard; the language is more complex than people remember,
and then there's the preprocessor, and finally the problem of doing something with the parse. C++ includes essentially all of C, and with C++11 here the problem is even worse.
People can often hack a 98% solution for a limited set of inputs, often with regexes in Perl or some other string hackery. If that works for you, then fine. Usually what happens is that 2% causes the hacked parser to choke or to produce the wrong answer, and then you get to debug the result and hand hack the 98% solution output.
Hacked solutions tend to fail pretty badly on real header files, which seem to concentrate weirdness in macros and conditionals (sometimes even to the point of mixing different dialects of C and C++ in the conditional arms). See a typical Microsoft .h file as an example. This appears to be what OP wants to process. Preprocessing gets rid of part of the problem, and now you get to encounter the real complexity of C and/or C++. You won't get a 98% solution for real header files even with preprocessing; you need typedefs and therefore name and type resolution, too. You might "parse" FOO X; that tells you that X is of type FOO... oops, what's that? Only a symbol table knows for sure.
GCCXML does all this preprocessing, parsing, and symbol table construction ... for the GCC dialect of C. Microsoft's dialect is different, and I don't think GCCXML can handle it.
A more general tool is our DMS Software Reengineering Toolkit, with its C front end; there's also a C++ front end (yes, they're different; C and C++ aren't the same language by a long shot). These process a wide variety of C dialects (both MS and GCC when configured properly), does macro/conditional expansion, builds an AST and a symbol table (does that name and type resolution stuff correctly).
You can add customization to extract the information you want, by crawling over the symbol table structures produced. You'll have to export what you want to C# (e.g. generate your C# classes), since DMS isn't implemented in a .net language.
In the most general case, header files are only usable, not convertable.
This due the possibility of preprocessor (#define) use of macros, fragments of structures constants etc which only get meaning when used in context.
Examples
anything with ## in macros
or
//header
#define mystructconstant "bla","bla"
// in using .c
char test[10][2] ={mystructconstant};
but you can't simply discard all macros, since then you won't process the very common calling convention macros
etc etc.
So header parsing and conversion is mostly only possible for semi automated use (manually run cleaned up headers through it) or for reasonably clean and consistent headers (like e.g. the older MS SDK headers)
Since the general case is so hard, there isn't much readily available. Everybody crafts something quick and dirty for its own headers.
The only more general tool that I know is SWIG.

how to break up the code in a method body into statement by statement symbols/"tokens"

I'm writing something that will examine a function and rewrite that function in another language so basically if inside my function F1, i have this line of code var x=a.b(1) how do i break up the function body into symbols or "tokens"?
I've searched around and thought that stuff in System.Reflection.MethodInfo.GetMethodBody would do the trick however that class doesn't seem to be able to have the capabilities to do what i want..
what other solutions do we have?
Edit:
Is there anyway we can get the "method body" of a method using reflection? (like as a string or something)
Edit 2:
basically what I'm trying to do is to write a program in c#/vb and when i hit F5 a serializer function will (use reflection and) take the entire program (all the classes in that program) and serialize it into a single javascript file. of course javascript doesn't have the .net library so basically the C#/VB program will limit its use of classes to the .js library (which is a library written in c#/vb emulating the framework of javascript objects).
The advantage is that i have type safety while coding my javascript classes and many other benefits like using overloading and having classes/etc. since javascript doesn't have classes/overloading features natively, it rely on hacks to get it done. so basically the serializer function will write the javascript based on the C#/VB program input for me (along with all the hacks and possible optimizations).
I'm trying to code this serializer function
It sounds like you want a parse tree, which Reflection won't give you. Have a look at NRefactory, which is a VB and C# parser.
If you want to do this, the best way would be to parse the C#/VB code with a parser/lexer, such as the Gardens Point Parser Generator, flex/bison or ANTLR. then at the token level, reassemble it with proper javascript grammar. There are a few out there for C# and Java.
See this answer on analyzing and transforming source code
and this one on translating between programming languages.
These assume that you use conventional compiler methods for breaking your text into tokens ("lexing") and grouping related tokens into program structures ("parsing"). If you analysis is anything other than trivial, you'll need all the machinery, or it won't be reliable.
Reflection can only give you what the language designers decided to give you. They invariably don't give you detail inside functions.
If you want to go from IL to other language it may be easier than parsing source language first. If you want to go this route consider reading on Microsoft's "Volta" project (IL->JavaScript), while project is no longer available there are still old blogs discussing issues around it.
Note that reflection alone is not enough - reflection gives you byte array for the body of any particular method (MethodInfo.GetMethodBody.GetILAsByteArray - http://msdn.microsoft.com/en-us/library/system.reflection.methodbody.aspx) and you have to read it. There are several publically available "IL reader" libraries.

translate C++/CLI into C#

How I can translate small C++/CLI project to c#
One roundabout, manual way would be to compile your C++/CLI project and open the output assembly in Reflector. Disassemble each class, have it convert the disassembled IL to C#, and save that code off.
As for an automatic way to do it, I can't think of any off the top of my head.
Those things being said, are you sure you really want to convert your project to C#? If your C++/CLI project uses any unmanaged code, you'll have a difficult time coming up with a purely managed equivalent. If the project is more or less composed of pure CLR code, and it was written in C++/CLI for the sake of being written in C++/CLI, I can understand wanting to convert it to C#. But if there was a reason for writing it in C++/CLI, you may want to keep it that way.
IMHO, line by line is the best way. I've ported several C++ style projects to a managed language and I've tried various approaches; translators, line by line, scripting, etc ... Over time I've found the most effective way is to do it line by line even though it seems like the slowest way at first.
Too much is lost in a translator. No translator is perfect and you end up spending a lot of time fixing up the translated code. Also, translated code as a rule is ugly and tends to be less readable than hand crafted code. So the result is a fixed up, not very pretty code base.
A couple of tips I have on line by line
Start by defining all of the leaf types
For every type that has a non-trivial (freeing memory) destructor, implement IDisposable
Turn on the FxCop rule that checks for lack of Dispose calls to catch all of the places use used stack based RAII and missed it
Pay very close attention to the uses of byref in C++.
I haven't tried it, but I just googled it and found this: http://code2code.net/
According t it, you shouldn't fully rely on the code it produces:
You accept that this page does only half the work.
Futher work on your part is required. In most cases, the translated code will not even compile.
Also, read this: Translate C++/CLI to C#

Categories

Resources