Related
I have a game server which is made in Java. I want to make a plugin system that loads a .NET DLL and calls events / functions inside that DLL, then inside those I'll have to call functions in the game server (Java). The only part that is giving me trouble at the moment is how to interface java and a .NET dll.
I've been searching and found some things but they were all based on products and I want to make my own interface for that. Ah, not to mention it needs to have high performance, the code will be called a lot of times in a second if it has to. Could someone point or give-me ideas how could I work this out?
EDIT:
To make it more explicit:
Game Server (Java application) calls a function in .NET dll
The .NET function just called by java, calls multiple functions from Game Server (Java Application).
Take a look at jni4net if you're targeting Windows. It's an alpha quality release, but Robocode already uses it to run .NET robots inside the Java runtime.
Another option is to use a high-performance messaging approach. You'll need a second process - likely a .NET plug-in host. That process then exchanges messages with the main Java game process. Messaging libraries like 0MQ are pretty darn fast but may not be fast enough for what you have in mind. In addition, you'll have to create a lot of message plumbing which may be cost/time prohibitive.
Try using iKVM:
IKVM.NET is an implementation of Java for Mono and the Microsoft .NET
Framework. It includes the following components:
A Java Virtual Machine implemented in .NET
A .NET implementation of the Java class libraries Tools that enable Java and .NET
interoperability
http://www.ikvm.net/
If you only have a few methods you are calling you might just use JNI and do it yourself instead of a 3rd Party tool (though I admit I don't know the details of jni4net). Just a word of caution, the project I'm on had to do a similar thing (C# -> C/C++ -> Java via JNI) and we had nothing but problems with it. Problems mainly because the java api didn't have any good documentation so that might have been part of it. If at all possible try to keep it to one language but if that is not possible, make sure you do lots of error checking. When the app crashes, it is very hard to find the problem (unless you own both the java and C# sutff). Just my $0.02...
For a large application written in C++ using Visual Studio 6, what is the best way to move into the modern era?
I'd like to take an incremental approach where we slowly move portions of the code and write new features into C# for example and compile that into a library or dll that can be referenced from the legacy application.
Is this possible and what is the best way to do it?
Edit: At this point we are limited to the Express editions which I believe don't allow use of the MFC libraries which are heavily used in our current app. It's also quite a large app with a lot of hardware dependencies so I don't think a wholesale migration is in the cards.
Edit2: We've looked into writing COM-wrapped components in C# but having no COM experience this is scary and complicated. Is it possible to generate a C# dll with a straight-C interface with all the managed goodness hidden inside? Or is COM a necessary evil?
I'd like to take an incremental
approach where we slowly move portions
of the code
That's the only realistic way to do it.
First, what kind of version control do you use? (If you use branching version control that allows you to make experiments and see what works, while minimizing the risk of compromising your code; others are OK also, but you'll have to be really careful depending on what you are using).
Edit: I just saw you are using SVN. It may be worthwile to move to mercurial or git if you have the liberty to do that (the change provides a quantum leap in what you can do with the code-base).
and write new features into C# for
example and compile that into a
library or dll that can be referenced
from the legacy application.
That's ... not necessarily a good idea. C# code can expose COM interfaces that are accessible in C++. Writing client code in C++ for modules written in C# can be fun, but you may find it taxing (in terms of effort to benefits ratio); It is also slow and error-prone (compared to writing C# client code for modules written in C++).
Better consider creating an application framework in C# and using modules (already) written in C++ for the core functionality.
Is this possible and what is the best
way to do it?
Yes, it's possible.
How many people are involved in the project?
If there are many, the best way would be to have a few (two? four?) work on the new application framework and have the rest continue as usual.
If there are few, you can consider having either a person in charge of this, or more people working part-time on it.
The percentage of people/effort assigned on each (old code maintenance and new code development) should depend on the size of the team and your priorities (Is the transition a low priority issue? Is it necessary to be finished by a given date?)
The best way to do this would be to start adapting modules of the code to be usable in multiple scenarios (with both the old code and the new one) and continue development in parallel (again, this would be greatly eased by using a branching distributed version control system).
Here's how I would go about it (iterative development, with small steps and lots of validity checks in between):
Pick a functional module (something that is not GUI-related) in the old code-base.
Remove MFC code (and other libraries not available in VS2010 Express - like ATL) references from the module picked in step 1.
Do not attempt to rewrite MFC/ATL functionality with custom code, unless for small changes (that is, it is not feasible to decide to create your own GUI framework, but it is OK to decide to write your own COM interface pointer wrapper similar to ATL's CComPtr).
If the code is heavily dependent on a library, better separate it as much as possible, then mark it down to be rewritten at a future point using new technologies. Either way, for a library heavily-dependent on MFC you're better off rewriting the code using something else (C#?).
reduce coupling with the chosen module as much as possible (make sure the code is in a separate library, decide clearly what functionality the module exposes to client code) and access the delimited functionality only through the decided exposed interface (in the old code).
Make sure the old code base still works with the modified module (test - eventually automate the testing for this module) - this is critical if you need to still stay in the market until you can ship the new version.
While maintaining the current application, start a new project (C# based?) that implements the GUI and other parts you need to modernize (like the parts heavily-dependent on MFC). This should be a thin-layer application, preferably agnostic of the business logic (which should remain in the legacy code as much as possible).
Depending on what the old code does and the interfaces you define, it may make sense to use C++/CLI instead of C# for parts of the code (it can work with native C++ pointers and managed code, allowing you to make an easy transition when comunicating between managed .NET code and C++ native code).
Make the new application use the module picked in step 1.
Pick a new module, go back to step 2.
Advantages:
refactoring will be performed (necessary for the separation of modules)
at the end you should have a battery of tests for your functional modules (if you do not already).
you still have something to ship in between.
A few notes:
If you do not use a distributed branching version control system, you're better off working on one module at a time. If you use branching/distributed source control, you can distribute different modules to different team members, and centralize the changes every time something new has been ported.
It is very important that each step is clearly delimited (so that you can roll back your changes to the last stable version, try new things and so on). This is another issue that is difficult with SVN and easy with Mercurial / Git.
Before starting, change the names of all your project files to have a .2005.vcproj extension, and do the same for the solution file. When creating the new project file, do the same with .2010.vcxproj for the project files and solution (you should still do this if you convert the solutions/projects). The idea is that you should have both in parallel and open whichever you want at any point. You shouldn't have to make a source-tree update to a different label/tag/date in source control just to switch IDEs.
Edit2: We've looked into writing
COM-wrapped components in C# but
having no COM experience this is scary
and complicated.
You can still do it, by writing wrapper code (a small templated smart pointer class for COM interfaces wouldn't go amiss for example - similar to CComPtr in ATL). If you isolated the COM code behind some wrappers you could write client code (agnostic of COM) with (almost) no problems.
Is it possible to generate a C# dll
with a straight-C interface with all
the managed goodness hidden inside? Or
is COM a necessary evil?
Not that I know of. I think COM will be a necessary evil if you plan to use server code written in C# and client code in C++.
It is possible the other way around.
Faced with the same task, my strategy would be something like:
Identify what we hope to gain by moving to 2010 development - it could be
improved quality assurance: unit testing, mocking are part of modern development tools
slicker UI: WPF provides a modern look and feel.
productivity: in some areas, .NET development is more productive than C++ development
support: new tools are supported with improvements and bugfixes.
Identify which parts of the system will not gain from being moved to C#:
hardware access, low-level algorithmic code
pretty much most bespoke non-UI working code - no point throwing it out if it already works
Identify which parts of the system need to be migrated to c#. For these parts, ensure that the current implementation in C++ is decoupled and modular so that those parts can be swapped out. If the app is a monolith, then considerable work will be needed refactoring the app so that it can be broken up and select pieces reimplemented in c#. (It is possible to refactor nothing, instead just focus on implementing new application functionality in c#.)
Now that you've identified which parts will remain in C++ and which parts will be implemented in c#, (or just stipulate that new features are in c#) then focus turns to how to integrate c# and c++ into a single solution
use COM wrappers - if your existing C++ project makes good use of OO, this is often not as difficult as it may seem. With MSVC 6 you can use the ATL classes to expose your classes as COM components.
Integrate directly the native and c# code. Integrating "legacy" compiled code requires an intermediate DLL - see here for details.
Mixing the MFC UI and c# UI is probably not achieveable, and not adviseable either as it would produce a UI mix of two distinct styles (1990s grey and 2010 vibe). It is simpler to focus on achieving incremental migration, such as implementing new application code in c# and calling that from the native C++ code. This keeps the amount of migrated c# code small to begin with. As you get more into the 2010 development, you can then take the larger chunks that cannot be migrated incrementally, such as the UI.
First, your definition of modern era is controversial. There's no reason to assume C# is better in any sense than C++. A lot has been said on whether C# helps you better avoid memory management errors, but this is hardly so with modern facilities in C++, and, it's very easy to do mess with C# in terms of resource acquisition timing, that may be dependent on what other programs are doing.
If you move straight from 6 to 2010 you may end up with some messed up project settings. If this isn't a fairly large project, and it's one of few that you need to convert, then that should be fine. Just open it in 2010, and follow the conversion wizard. Make sure to back up your project first, and verify your project settings when you're done.
In my opinion though the best way is to convert it step by step through each iteration of Visual Studio. I had to modernize 1400 projects from 2003 to 2010, and the best way that I found was to convert everything to 2005, then to 2008, and then finally to 2010. This caused the least amount of issues to arise for me.
If you only have 6 and the newest Visual Studio you may end up just having to try and go straight to the new one using the wizard. Expect some manual cleanup before everything builds correctly for you again.
Also, one more time, BACK IT UP FIRST! :)
High-level C++ code calling low-level C# code doesn't look like a good idea. The areas where .NET languages are better, are user interface, database access, networking, XML files handling. Low-level stuff like calculations, hardware access etc. is better to keep as native C++ code.
Moving to .NET, in most cases it is better to rewrite UI completely, using WPF or Windows Forms technologies. Low-level stuff remains native, and different interoperability technologies are used to connect C# and native code: PInvoke, C++/CLI wrappers or COM interoperability. After some time, you may decide to rewrite low-level native components in C#, only if it is really necessary.
About compiling native C++ code in VS2010 - I don't see any problems. Just fix all compilation errors - new compilers have more strict type checking and syntax restrictions, and catch much more bugs at compilation time.
Not sure why so many folks are advocating for COM. If you haven't already got a lot of COM in there, learning how to do it on the C++ side is going to hurt, and then you're using the slowest possible interop from the managed side. Not my first choice.
Ideally you have refactored your UI from your business logic. You can then build a new UI (WPF, WinForms, ASP.NET, web services that support some other client, whatever) and call into your business logic through P/Invoke or by writing a C++/CLI wrapper. #mdma has good advice for you assuming that the refactoring is possible.
However if you were paying me to come in and help you my very first question would be why do you want to do this? Some clients say they don't want to pay C++ devs any more, so they want all the C++ code gone. This is a scary objective because we all hate to touch code that works. Some clients want to expose their logic to ASP.NET or Reporting Services or something, so for them we concentrate on the refactoring. And some say "it looks so 1999" and for them I show them what MFC looks like now. Colours, skinning/theming including office and win7 looks, ribbon, floating/docking panes and windows, Windows 7 taskbar integration ... if you just want to look different, take a look at MFC in VS 2010 and you might not have to adjust any code at all.
Finally to make non-Express versions of VS 2010 affordable look into the Microsoft Partner Program. If you have sold your software to at least 3 customers who still speak to you, and can get through the Windows 7 logo self test (I have got VB 6 apps through that in a day or two) then you can have 5-10 copies of everything (Windows, Office, VS) for $1900 or so a year, depending on where you live.
To start I'd try and keep as much code as possible to avoid a rewrite. I'd also remove all unused code before starting the conversion.
Since VC++ 6.0 Microsoft changed the MFC libraries and the C++ Standard Library.
I recommend to start building your DLLs with no dependencies, then looking at your third party libraries, and then rebuild one dependent DLL/EXE at a time.
Introduce unit tests to make sure the behaviour of code does not change.
If you have a mixed build, using different versions of VC++, you need to guard against passing resources (file handles) between DLLs that use different versions of the VC runtime.
If at all financially possible I would strongly consider just paying the money for the version of Visual Studio that you need because you could very well lose more money on the time you spend. I do not know enough about the express editions to give a good answer on them but when integrating some code from a subcontractor that was written in C++ I used C++ / CLI. You will probably be able to reuse most of your codebase and will be familiar with the language but you will also have access to managed code and libraries. Also if you want to start writing new code in C# you can do that. The biggest problem I had with it was that in VS 2010 there is no intellisense in C++ / CLI.
Visual Studio 6 is legendary for being buggy and slow. Moving into the modern era would best be done by getting a new compiler. What is probably the easiest thing to do is write the legacy app into a DLL, then write your exe into C# and use P/Invoke. Then you never have to touch the old code again- you can just write more and more in C# and use less and less of the old DLL.
If your old code is very heavily OO, you can use C++/CLI to write wrapper classes that allow .NET to call methods on C++ objects, and collect them too if you use a reference counted smart pointer.
You can use C# to write your new components with a COM or COM+ (System.EnterpriseServices) wrapper, which will be callable from your existing C++ code.
How is winforms programming in visual c++/c# different from windows programming in visual c++(MFC).
Also I want to know whether C# is strong enough to do Windows programming as in other than forms.
I'm not sure if anyone can give one single answer to this question, I can just try to point out a few of the many differences:
C# and C++ are quite different: Memory management, package structure, class layout, events/delegates, generics/templates... Even writing non-GUI apps is completely different in C++ and C#. Many of the features of the C# language are very helpful if not even designed for GUI development.
Winforms has a very good visual designer support if compared to MFC. For 95% of all apps, you'll be a lot more productive using winforms. This is especially true for custom controls (either your own or third party)
MFC on the other side provides more framework support (document/view structure etc.).
For some applications, MFC apps may seem more responsive. In most of these cases, a winform application can be optimized to have the same performance, but this is above the average winforms developer level (which is generally lower than the knowledge level of MFC programmers).
MFC encapsulates the WIN32 API more directly than Winforms do. There are cases where you need to access the WIN32 API even from winforms directly. Then it is not always clear (and not well documented), how to do this. Again, a typical winforms programmer has less knowledge of the WIN32 API than a MFC programmer, so in these cases he will run into troubles more likely.
I think winforms is well supported and you can solve pratically all GUI/NON-GUI tasks. For most tasks, it will be easier to write a C# program.
I'm sure, there are much more arguments pro/contra, I just noted the few that came into my mind...
There are a few notable differences:
You'll eventually be more productive as it is much easier to do (.net)
The language helps you from making a lot of common mistakes (null pointers, overflows, leaks)
The framework is a lot (and really I mean a lot) more clean than MFC
In essence you can do almost anything. The least common 0.01% of things you need to do through direct win32 DLL invokes (or use a wrapper or library someone else made)
As a professional, I have to admit that I prefer to use Delphi instead of C++ for any WIN32/Desktop development. If you're going to build GUI applications that are client applications or stand-alone applications then you might find that Delphi (and C++Builder) has far more visual components than .NET, at this moment. That's because .NET is still more popular for web development and service applications.
Doesn't mean that Delphi (or C++) is more powerful than .NET, since .NET is gaining quickly on the GUI application level. WPF/Silverlight is going to promise a lot of new possibilities for developers.
Another reason why many people are still using Delphi/C++ for WIN32 is because they still have lots of legacy code. And some of this code has already been working for over a decade and only needs additional maintenance. Rewriting those projects in C#/.NET would be way too expensive. People are considering this but existing code has proven itself already. New code will introduce new bugs.
With C# you're not going to do Windows development. You're doing .NET development and some parts of .NET will allow you to use the Windows functionality. However, a major part of the .NET classes are actually wrappers around the Windows API, making it easier to use those functions. But not everything is already implemented in .NET, so there's still a lot of work that needs to be done.
The danger of .NET development is what I like to call, the ".NET Hell". When .NET was introduced, people said it was going to end the DLL Hell that was bothering every C++ developer on Windows. Well, It did end the DLL Hell, only to replace it with the .NET Hell, where multiple versions of the same assembly are still able to cause lots of problems. So, in that regard, nothing much has changed. You're still depending on a certain runtime version of a specific library (especially with third-party libraries) so there's no real gain here.
Still, I really like .NET development, most of all because more and more applications are run as a service (SAAS) instead of the old-fashioned desktop application. Basically, you'd only need a web browser to use those applications, thus becoming less dependent on certain hardware requirements. Here lies the real strength of .NET development.
I learned windows programming using Visual C++, and the Win32 API. Nowadays, it seems most apps are being developed in .NET using C#. I understand that most of the time there isn't much performance difference between native code and managed code. So I'm wondering, if I were to start writing a new desktop app today, is there any reason (other than the fact that I'm more familiar with C++), that I might want to write it in non-managed C++ instead of .NET? Are there still some advantages to using C++ and native code? Or has that method been more-or-less replaced with .NET on the Windows platform?
Of course I know that people who are writing low-level device drivers and similar programs wouldn't do it in .NET. I'm asking with reference to typical client-facing apps that don't make direct hardware calls.
IMO the most important one for small downloadable applications is that native code does not need the .NET runtime. While broadband becomes more and more common not nearly everybody has it yet.
Some people may be disappointed to see that your 2 MB application actually requires another 20MB of framework download and a bothersome installation process to run. If they are not sure whether or not they really need your application in the first place, they might just delete it before even giving it a try and turn to a competing product.
Performance (certain situations, such as graphics)
Memory footprint (as Mancuso said)
Use of existing libraries
No need for a runtime
Finer control
To list a few.
However, you may also want to look at the question from the opposite angle to fairly evaluate which language to use.
Additionally, you could use C++/CLI to incorporate both native and .net code.
If your application needs to be able to run without an installation (i.e. if you can't or shouldn't do something like install the .NET framework), you can't count on .NET being on a windows machine (pre-Vista). Lots of utility applications can fall in this category.
I would recommend to write every desktop application in managed code. .NET/C# is a great platform to do so.
My reasons:
Performance penalty is negligible. Google for benchmarks if you don't take my word. What matters more is the code itself. You can write O(n^m) algorithms in C++ or .NET/C#. JIT engines are very mature these days.
Unmanaged C++ has major drawbacks when it comes to unit testing, mocking and refactoring. It's very cumbersome and inflexible. Reflection allows managed code to make such things very convenient.
Deployment is a small issue. However, creating a setup which checks for the necessary .NET preconditions and installs them automatically is a no-brainer.
Compilation is quicker, no linker! It even happens in the background when you edit the code.
.NET library support is way better and cleaner than STL, MFC and boost.
No header files and macros. They are just error prone.
Security! Good bye buffer overflows, bad pointers, uninitialized variables...
Exceptions. Clear exception hierarchy in .NET. C++ exceptions are messed up.
Memory footprint. But unless you're developing for a severely handicapped machine memory-wise, it really shouldn't be an issue for most applications.
If you can afford the dependency on the stack, go for .NET
Modern, elegant, powerful and as a result much quicker to develop for.
But realize that you chain your app to it - to the language and the framework, if you forsee a future where you may want to escape this, then better think twice.
Win32 is old and clunky, but it works on virtually any Windows version without extra dependencies, and your code can be in plain, portable, C/C++.
+1 for not having to require a .NET package/install on the target machine(s). This is still a big issue.
When all machines have mono or NET it won't be such a big deal.
Two things that I can think of.
Protection of intellectual property. It's infinitely harder for someone to reverse engineer an Unmanaged C++ app. Managed .Net or Java apps can be easily de-compiled this is not the case with Unmanaged C++.
Speed. C++ is closer to hardware and has a smaller memory footprint as the other comment mentioned. This is why most video games continue to be written in C++ and inline assembly.
.Net programs also have a support lifetime, where native do not really. Native will run for many years across different OS's without requiring updates.
.Net programs can be hosed by bad .Net configuration, native just keeps on running and is hardly effected by OS updates.
.Net programs startup slow and feel sluggish, native starts quick and runs quick.
.Net has to be coded for lowest common denominator (most distributed framework version), Native compiles all code into application - so use what you want.
Use Delphi for Native, not C++. .Net is partially based on Delphi RAD and Java backend.
Is there any work being done to create a C# compiler to produce native exe's? e.g. the output is a native exe and NOT a .NET assembly.
Why don't you try NGen. For exemple Paint.NET use nGen to create native images after installation.
If you want a standalone deployment (i.e. without needing the framework), there are a few options - see here. However, I'm not aware of anything that will reliably produce purely unmanaged code. What is the use-case you have in mind? For embedded etc there is micro-framework, CF, etc.
There is such solution for Mono, this is 'mkbundle' - static linking instead of using JIT/CLR/GAC, I guess
You'd still have to provide the libraries in some form so either you'd still have to have a runtime installed, or the native exe would have to be huge.
There are two active projects. They are geared toward CIL-based operating systems, but the current iteration of MOSA Compiler Framework runs on Windows (unit tests etc.) and has limited boot support. Cosmos used to have a Windows architecture and a few plugs, but they don't do Windows any more - only booting into a CIL environment.
Cosmos is much futher along however, they have pretty much nailed object support. MOSA is only bare-metal (static methods) for now - although it is done the 'proper' way and well unit-tested (and I think making faster progress). Give it a few more months and then go back and have a look.
Niether has a JIT at the moment (which doesn't matter since you don't want one). It is all compiled to machine code ahead of time.
MOSA (Compiler Framework)
COSMOS (IL2CPU)
.NET linker
You might find this interesting to read as well: .NET Internals and Native Compiling.
Note that for the reflection to work a lot of information about the code will always have to present.