Converting a C++ program into C# - c#

I'm working on a project where I'm converting C++ code to C# manually. I have working knowledge of C# but I've never used C++ before.
What I need to know is how to deal with the header files, since C# does't have anything like that. Say I have buffer.h and buffer.cpp, would I just convert them both and include them in the same buffer.cs file?
Is the C++ header file in any way related to an Ada spec file?

The distinction between includes ".h files" and source ".cpp files" is only one of convention. The convention is that declaration (functions, classes, etc) are in .h files which are #included in implementation (definition), or .cpp files. For most cases you're fine in collapsing X.h and X.cpp to a single X.cs file.
That said, you still need to take a look at what is going on in each file. A basic understanding of C++ would go a long way here, and something I strongly recommend you acquire before you get too far into your translation.

It might help you to think of a C++ header file as containing two major types of things: the class definition, which defines its member data and "interface" (not to be confused with a C# interface type) and "other stuff". The class definition part contains method prototypes and class member variables.
The good news concerning the prototypes is that you simply don't need them in C#. Clients of your class receive prototype information from the implementation itself via the assembly for the namespace. The data members are contained within your C# class implementation, typically as private members which are exposed through C# properties.
The "other stuff" mentioned above can include #defines, which you typically want to turn into const definitions in C#. Other things such as enumerations have equivalents in C# which you of course move into the .cs file for your class.

Related

Why C++/WinRT requires IDL files for XAML?

For C#,, XAML transpiles to .cs (*.g.cs) files and need no IDL files.
Similarly in C++, Why can't XAML be transpiled to .cpp (*.g.cpp) files and Need any IDL files at all ?
I don't understand.
There's a fair bit of confusion in the question as to how the individual pieces fit together. The main driver for the translation is the IDL file. Irrespective of whether it is authored by a developer or synthesized by the IDE, it is the IDL that produces WINMD (Windows Metadata) files describing the interfaces and runtime classes in a language-agnostic fashion.
The WINMD's are used by all tooling that needs to look up types, query for members (such as properties, events, delegates), and produce application packages.
XAML, on the other hand, isn't part of the compilation process at all. While some of its contents are verified at compile time, it usually gets translated into a compact binary representation (XBF) that's loaded and parsed at runtime to instantiate types.
The question as to why IDL's are required with C++/WinRT (and not with C# or C++/CX) is easily answered: It's simply not possible to derive enough information from C++ class definitions to unambiguously deduce the required metadata.
As an easy example, consider properties. While both C# as well as C++/CX have dedicated language constructs to describe properties, this is not the case in C++. C++/WinRT projects properties to member functions that take zero or one argument (for getters and setters, respectively). If you were to automatically deduce metadata from a C++ class definition, a tool would have to disambiguate between a property and a method. There are other challenges, too, and while Kenny Kerr has repeatedly voiced the desire to get better IDE support for C++/WinRT, the Visual Studio team doesn't seem to care much (see this comment, for example).
For the foreseeable future you should be prepared to author IDL files if you choose to use C++/WinRT.

.cs class definitions auto-created in .ts

I need to have a REST server (written in C#) pass a JSON object to/from my typescript client running in a browser. The best way to do this is define the class on the C# side that then creates a JSON object passed to the client where that JSON object matches the class structure in the client.
Which leads to the obvious question - is there a way to define the classes in C# and then run some program that will create the .ts class definitions? Or the reverse where I write out the classes in .TS and a program then creates matching .cs classes?
What I want to avoid is having to make sure any member added on one side is then added exactly the same on the other side.
And in a perfect world, the comments written for the class members are carried across too.
Update: I know I can write such a tool. However I'm hoping it already exists as that's a lot of work.
Type lite http://type.litesolutions.net/ gets you halfway. Just the data member signature.
As you know json doesn't carry behaviour just data. So no functions will not be available on the other side. It's not a "transpiler"
And in a perfect world, the comments written for the class members are carried across too.
Doesn't do this.
I created a library which allows you to create JS-models for knockout and backbone out of c#-classes (mainly for domain-classes, so it comes with stuff like DataAnnotations-support, etc).
I added support for Typescript, as well as a small tool to create the files directly.
Check it out and if you have time, I'd love some feedback :)
https://jsmapper.codeplex.com/
Cheers,
Richard

Generate C# wrapper from C include file

Suppose I have a dll written in pure C. I have an inculde file (.h) so I can use the dll from a VS 2012 C project.
Is there any way to generate a C# wrapper class based on the metainfo in the include file, or I must write all the [DllImport]... manually? The C source code for dll is also available.
(Please note: This is not a COM library)
Thanks in advance
There are tools that can help, but by and large you have to write the wrapper code yourself to some degree. The main reason being that a C header file does not fully specify the interface. For instance, consider this function:
void foo(int* x);
Does this function receive a pointer to a single int, or does it receive a pointer to an array? There's no way for you to tell with just this information. So, any tool that creates wrappers must also use some form of annotation to fully describe the semantics of the functions. If those annotations are not present you would need to create them. At which point it probably becomes quicker and easier to write the wrapper manually.
As an alternative to writing C# pinvokes you can use a mixed mode C++/CLI assembly. This can include the header file and link against the import library. Then all you need to do is write a C++/CLI ref class to wrap the interface, and add the C++/CLI assembly as a reference to your C# project.

Namespace Constants in SWIG

The issue is fairly simple, I have some constants in a C++ namespace that I would like to wrap using SWIG 2.0.8. It looks something like this:
namespace Example {
static const float PI = 3.14159f
...
/* Lots of classes are here */
}
Unfortunately SWIG handles this rather awkwardly. In the C# case, it adds the constants to a class with the same name as the namespace so it must be accessed by using Example.Example.PI even when I am explicitly using Example (due to masking by the module name).
In Java, its even worse as it does not treat it as a constant at all and I am forced to call it using Example.getPI() as a method call instead of a constant class variable.
If I move the constants to the global namespace, this seems to work but then the variables must be accessed using ExampleConstants.PI.
Ideally, I would like both languages to be able to access the constants via Example.PI to be consistent with C++. But a compromise that I would be happy with is if I could have a Constants class inside my namespace so that I can use Constants.PI in either language. But of course, C++ does not allow non-integral types to be defined inside a class and this is still not solving the issue in Java.
Is there any elegant way to handle these namespace constants with SWIG?
And if not, is there a way I can manually add a Java or C# class to define them?
I solved similar problem for C++ - C#. I am not sure if this is exactly what you are looking for, but I hope you will find some info useful for you.
I have not touched Java code in my project.
Swig solution.
I created class with public static parameterless functions in C++.
Then I exported them to C# using SWIG.
I specified namespace for C# in command line with -namespace <name> key. More details available at page SWIG and C#
As a result you can impelement solution to access your constant with Constants::PI() and Constants.PI()
Direct solution
If you would like not to use SWIG or other library, you should use PInvoke. There are a lot details and special cases when working with it. Most comprehensive article on subject I have found is Mono Interop with Native Libraries
You should consider JNI for Java.
Note, that C++ functions are exported without namespaces as pure C functions and you should create C# class and create functions with DllImport attribute to wrap functions back to namespaces.
In general if your C++ interface is more or less fixed and/or small I would adhere direct solution, because SWIG layer has many-many specific cases which should be learned along with PInvoke/JNI. But if you C++ interface frequently changed and requires a lot of effort to keep C++, C# and Java consistent, you defenitely need to consider SWIG.
You may find non-trivial example using PInvoke at https://stackoverflow.com/a/11909571/13441
Concerning C++ constants. You can specify C++ constant inside class, refer to C++ static constant string (class member) for details.
I use SWIG 1.3.40.
Hope this is helpful.

C# .net - Dll Naming Conventions in Interface / Implementation Scenarios

I need some suggestions for clever naming of dll and/or a hint if any naming conventions for the following scenario exist.
I have an interface definition and several types used by that interface definition encapsulated in one dll. Then I have an implementation of this interface in another dll.
The “special” thing about this situation is that I do not develop an application but more a collection of functionalities (aka framework) that is used by multiple applications of my company. These functionalities are accessed through its interface definition via MEF, so the user of this framework does usually not know, nor is it important to him, in which dll the implementation is (since he only needs to know and reference the dll containing the interface definition). Just in really uncommon cases he might want to know how the dll (the one containing the implementation) is named, because he wants to replace the implementation with his own.
I created some requirements for my dll naming:
The dll with the interface definition needs to be well named because this is the dll the user is referencing.
The namespace of the interface definition dll needs to be very well named (and be very intuitive) so the user really expects this definition in this namespace, where it would be the optimum that the namespace equals the solution structure.
The implementation dll must be named very clear, so the user can identify the dll in the working directory to remove it and install an own implementation.
The namespace of the implementation does not really matter since its only used internally.
The dll names should not be too long.
First, I came up with the idea to group all interface definitions of a specific type in one dll, that would create a very well named namespace since I can group for example all “services” in a dll called MyCompany.Services.dll, put all definition and types in that root (which creates the namespace MyCompany.Services), and therefore have kept the solution structure equal to the namespaces (which might be alo discussed here if this is useful or not).
But that generates a big problem:
If I signature the dlls and change something in my MyCompany.Services.dll, I have to recompile all implementation dlls even if this change only affects one of this n dlls. At that point I thought about putting each interface definition and ity types in an own dll (as described in the beginning of this post).
My 2 cents worth:
Use a common top-level namespace so everything that's part of your framework can be easily identified. You might not "need" it but it just seems silly not to.
Use descriptive names. Things like Basti.SpecialFramework.Interfaces.DataAccess.Customer would make a lot of sense to me.
Structuring the namespace around the structure / architecture of your system makes lots of sense.
Having a well structured namespace tree will help the interpretation of key works / terms in the same place, e.g: Basti.SpecialFramework.Interfaces.DataAccess.Customer vs Basti.SpecialFramework.BaseImplementations.DataAccess.Customer
Treat it a bit like developing Information Architecture or doing usability testing: come up with a draft set of names and see if your friends can figure it out. Do the eqivalent of a Card Sorting exercise - do you structure it: [Layer].[Interface / BaseImplementation] or [Interface / BaseImplementation].[Layer]? (I'm not sure exactly how you would do the card sorting exercise but I can see some strong parallels).
Descriptive names tend to be long, this goes aganist your last point; I agree long names might not be "easy" and "convenient" but if they clearly convey what I need to know I would be okay with that.
By the way: I'm sure naming conventions exist for DLLs and Assembilies - I just don't know them off the top of my head. I guess I could Google / Bing them but I guess you've done that already.

Categories

Resources