How to create C# custom controls from c/cpp - c#

Can somebody shed some light on how to create c# custom controls from vc? I need to create some graphical controls which will be used in a C# project like the default controls, because performance is important and it's on a low performance windows CE device, I guess I have to do it in c/cpp.

The simple, straightforward answer is that you can't. Period. The Compact Framework doesn't support managed C++ (C++/CLI). Now I suppose you could create the UI component as a COM control, then hand-roll all of the COM interface stuff for the managed side, but that would be a nightmare to build, debug and especially deploy.
You're better off just dropping to unsafe code and using P/Invokes to the Win32 APIs you're after right in the C# code. For most things, you can achieve what you want and get good perf. If you have something that absolutely must be done in C for speed, then create a library that you pass in buffers to via P/Invoke. The Imaging library, for example, uses this type of mechanism for creating thumbnails, etc.

You can try to write a complete control in C and provide a very thin wrapper exposing what you need to control from say C#. It doesnt necessarily need to follow UserControl or Control's model if we are talking about Forms controls, which is somewhat complicated to get right, and where all the cost goes for those controls. Its very harsh.
You can also investigate WPF, which tries to get more done on the managed side, thus faster. It has its own complications. It will composite / "bitblit" usually fairly inteligently on its own, but goes overboard often, but its way faster (or can be) than a double buffer Forms control, which in the end will be doing the same composite in double buffer mode, but slower with a larger flurry of faux win message handling. (To grossly oversimplify)
So rather than just saying NO, i think those are your options. Again, it is possible to control at arms-length, a well-written C side render and get near native performance.
Edit:
I missed the Windows CE part of the question. My bad. I dont know if what I said will apply.

I assume you're talking about WinForms and not Silverlight.
You don't need to.
.NET on Windows CE performs JIT of CIL (unlike the Micro Framework which interprets it, like old-school Java). There is no real performance penalty of writing controls in C#. The most expensive operation is painting, and if you use C# or C++ then you'd be doing this with GDI, and it's inside GDI's function calls where the expensive operations lie, the only thing you'd be saving is the marshalling between Managed and Native territories, but that really does count for very little.
The only situation where you might want to use C++ to create a Windows CE GUI was if you were working with video or an animation framework (like Flash), and if you were doing that then you'd use C++ entirely and not use .NET for any of your GUI.

Related

C#/GDI Converting to Universal Apps for Win10

I realize someone asked a similar question here but I think my question is from a different vantage point and I hope it might help people in the future understand their options.
Basic issue: I have written a C# App (obviously managed) as a normal application (non-universal) and in order to support a quick log window above an active typing area, I initially wrote some graphics using pure .net (GDI I believe). This worked initially but it became VERY slow sometimes and I want way better control over how it looks including some specialized graphics.
What I would like to do is rework the app AND find out which of the following makes the most sense for a Windows 10 Universal Application:
Call DirectX Directly from C# (from documentation this is either not-possible or not really ideal, base project for C# does not have directX like C++ does).
Call Managed Libraries from C++ and use DirectX as the Application Foundation.
Use C++/CLI and call managed code. (I believe this is not possible anymore).
Use SharpDX (I looked and it didn't seem available based on a question here).
Use another Third Party (such as Unity) but deal with game frameworks.
Other parameters: Since everything is C# already, would like to avoid total rework, however, if it's recommended I'm 100% ok with doing so. This is not a game application, though it needs performance like one on one of it's screens, it will mostly be driven by interfaces (could be XAML) and network data coming in on a separate thread. I also have no qualms about learning extensively (say a very different language from C# or C++) in order to complete this project because learning is value. If I am missing something glaringly obvious that would be great to know about it as well.

Extending C++ Win32 application with a C# WPF component

I need to add a new component to a C++ Win32 application (no CLR support) and I would like to implement the new component in C# and use WPF. This new component is basically a window with some controls, which I need to launch quickly from an option in the menu of the Win32 application. The new component and the existing application share some int values and both can modify these values and the other should be notified of changes.
What would be the best way to achieve this?
Thanks
If you want to do this without changing your C++ compilation you might look at calling the .NET assembly as via COM. MSDN describes how to expose .NET Framework Components to COM.
The way I've done this is basically:
Make a COM friendly class and interface in C#
Export the TLB from the DLL
GAC the DLL
Register the DLL using regasm.exe
import the TLB into my C++ code
CoCreateInstance using the __uuidof my C# class
However I haven't tried to do this with a UI component. If the WPF form is a modal dialog you should be OK. If not then I don't know if WPF will be happy with your message loop; you may need to give it a seperate thread so it can run its own loop.
Have you seen the MSDN docs on this subject?
A cursory read implies this is not possible without enabling /clr on your C++ code. if you are able to move to this model then the things you want seem do-able.
btw I would not implement update/signalling code on both sides of the managed/unmanaged boundary for your shared data. Decide where the data lives, and have that code provide a) thread-safe accessors and b) 'update event' wiring that are used by whoever needs to write the data and know about updates.
Check out Observer pattern for a description of how to implement notification to multiple consumers. This may be overkill for your case but useful background.
EDIT:
Until you get the two modules coresident, discussion of event notification design seems premature. If you really cannot build your native code with /clr then I don't see how your WPF component can be used without a separate process, and resulting complexity in interaction and performance hit. Can you re-implement this WPF functionality in native code?
On the other hand - if you plan on making more mods to this codebase, perhaps it's worth considering how hard it would be to port the native code to be /clr-ready. Inline assembler does not prevent use of /clr but it does make it harder, as I am sure you have seen here. My guess is that this would be less work than wiring up the WPF code externally.
The path of least resistance at this point may be to replicate your WPF component in native code. Long term taking the pain of converting your app to /clr may provide a better foundation though. Sorry there is no simple answer.
One way to achieve this is compile your C++ application as a C++/CLI application. Once it's a C++/CLI app, you can mix managed and native code easily, and even talk to managed components with ease.
Rather than mess with COM, I'd prefer to use C++/CLI as a glue layer - that does not require recompiling your entire app as C++/CLI.
That means:
Write the C# code you want.
Write a thin C++/CLI wrapper. This can reference (i.e. dynamically link) to the C# app. All it does is expose a native API around the .NET API. It takes some getting used to, but you can do pretty complex stuff here, including fairly fancy automagic interop via marshal_as. You'll compile this into a dll - a mixed mode DLL.
Your main app now links dynamically to the mixed mode DLL and includes the headers for its API. It can call functions as usual.
This is quite a bit nicer that COM, I think: it doesn't require the GAC, it has a lower overhead should performance ever matter, and exchanging complex datastructures including callbacks & deep object graphs is possible (though there is a learning curve here) quite cleanly by adding custom marshal_as templates/overloads.

Port unmanaged C++ project to C#

I need to port a C/C++ unmanaged project (VS 2008) to C# (preferably .net 3.5).
Are there any conversion-helping
tools; let's say something
translating the code syntax and
asking you verifications/modifications for each
problematic point (I guess I'm dreaming...)
Where can I find some useful howtos or articles about this translation.
They would be very useful if they contained specific hints like:
extern variables should be set in public static classes
(I don't know, I'm guessing...)
Please no suggestion like "You can call your c++ dll from .net", because I know it's possible, but just I can't.
Note:
The C/C++ project uses only STL and
other basic functions, no 3rd Party
libraries etc.
I can't use it directly or wrapped
from C# because our company needs to
mantain/modify the code and we're extremely
more skilled in C# than in C++.
It will cost you far more to convert it than to wrap it and pay a freelancer (like me) to help you out by changing the C++ code for you every few months (or every few years) when you need to make a change. There are some mechanical approaches but the bigger issue is that you can never really be sure that the new C# code does exactly what the old C++ code did. I have clients who have tried this and most gave up and threw the work away. The ones who succeeded did it very slowly, like this:
First, you wrap the old library and get your UI or whatever the new code is (web service, whatever) successfully calling the old library. This gets everyone some "bang for the buck" and buys you time to solve the "we can't maintain our old code" problem. You also develop a comprehensive test suite that proves what the old library does for various edge cases and strange things that only happen in the wild every few years. Over time, you move functionality from the old library into a new C# one and change the calling code to use the new library for that functionality. You move the most volatile parts, the things you change most often, out first. At every stage you run the test cases again to make sure your translation from C++ to C# didn't mess up the results it calculates. Maybe some of it you never move out, maybe in the end it is all moved. You stop when you feel the risk of being unable to maintain your own library and needing to pay someone to do it for you has dropped below the cost of continuing to translate it.
I recommend you have access to someone with good C++ skills when you start. You will probably run into things that don't make much sense to you. But you can get the value from the library pretty quickly, and still solve your underlying problem in the long term.
Depends on what you mean by port.
You can rewrite some of the stuff in C#. Not everything. Some HW or legacy libraries would have to be handled with C/C++ even if you port your own code. I don't know of any reliable automatic converter for C++->C#, and I doubt one can exist.
A better idea may be to wrap your existing code in new C# code. You could create an interop layer in C++/CLI, for example. Or you can communicate with your native code with something like Google Protocol Buffers, if you don't want to mix native/managed code in the same process.
I doubt code conversion tools would help. If you need to make some C++ work in some fashion with .NET, the easiest way is to write a managed C++ layer that wraps it and provides an interface for .NET apps to work with. But it depends on the code.
What is the purpose of rewriting and what does your code do? Does it interface with other components? Does it have a GUI? Is it a standalone executable or a library? Is it a COM / ActiveX server or does it use COM components? Does it link to other DLLs or use 3rd party libraries?
All these affect how you're going to port / rewrite from scratch your app. For example, if your code is an MFC app you may as well forget trying to salvage much code. If your app does http / high level networking stuff you may as well write from scratch. If your code low level you might have to refactor with some C# and some C++ accessible through a managed C++ layer.
Lots of choices and it really depends what your app is doing, how it was written etc.

WinForms or WPF or Qt for Windows GUI with C/C++ as backend

I am to develop an application on windows. I have never done that before ;-)
I need to do some heavy audio calculation, which has to be written in C/C++. This part will be a room correction algorithm which currently takes about 10 seconds per channel to run in Matlab. It has to be written in C/C++, since it might be ported to a DSP later on, which has to be programmed in C/C++.
Additionally, I need a GUI to review calculations, visualize results and modify calculation parameters. The tough part of this GUI will be lots of plotting of spectra, spectrograms, audio waveforms and the like.
Now, I hear that WPF is all the rage in Windows GUIs, but it seems to be limited to C#. Is there a simple way to integrate my C/C++ code with some C# GUI code? Or should I rather take WinForms and just write the whole thing in C++? Or would Qt work just as well and provide some cross-platform capabilities "for free"?
I have some experience with C/C++, Matlab and VST-development, but I never wrote a real application and honestly, I don't even know where to start.
Thank you in advance!
I think the biggest drawback to using WPF or WinForms is that you will have to program in two programming languages, which is a big logistics overhead.
I've seen this type of argument before: use C or C++ for low level, something else for high level. In this case Qt/C++ is as high level as WPF/WinForms, with the benefit of very easy integration of UI to your other C++ code.
For spectrograms and other graphs check out Qwt.
P.S: WPF is not all the rage on Windows, in fact the market is quite fragmented and WPF is one of the lesser used GUI toolkits. Most of the code out there uses MFC, WTL, Delphi, Win32, etc.
I have no experience on QT, but I can say that WPF is good but its not that good for high CPU intensive applications, plus you will not be able to directly integrate your c/c++ easily with WPF.
There will be huge learning curve and you will have to write COM Interfaces to communicate with C#/WPF and your native code. or Visual C++ .Net CLI, which is quite difficult and less tutorials are available.
But problem is you will not get any good support because lots of people only use C#, database apps only with WPF/WinForms. The best way to do is, you can write COM DLLs to integrate with WPF, but that will be difficult.
Instead there are various tools available now in MFC, and lot of other commercial libraries are available as well to write good UI in C++ MFC, where integration will be quite easier as you are familier with C++.
Or else Qt, if you already know it.
Libraries:
Prof-UIS
BCGSoft
There may be many, you can search for "MFC UI Elements", Library etc. I have used Prof-UIS way back in 2003-4 they are good.
WPF will tie you to Windows, but not to any language in particular. You can write WPF applications in C#, VB.NET, Managed C++ or any other .NET language.
Winforms is similarly tied to Windows, but you may be able to write your application in such a way that it also runs on Mono, and therefore is cross-platform. However, Winforms is far less capable toolkit when it comes to complex visualizations.
Interop between .NET and native applications is very strong, but it is sure to cause you at least a little pain. On the other hand, implementing the interface in a native environment may cause you even more pain.
If you're happy for your GUI to be tied to Windows and .NET, WPF is the best option for highly visual applications. If you don't want a dependency on .NET or Windows, Qt seems like your only option.

What can be done in VC++ (native) that can't be done with VC#?

What can be done in VC++ (native) that can't be done with VC#?
From what I can tell the only thing worth using VC++ native for is when you need to manage memory yourself instead of the CLR garbage collector, which I haven't seen a purpose in doing either (but thats for another question to be asked later).
Cross-platform development. Yes Mono exists, and Java's somewhat more predictable to have it function EXACTLY the same on more platforms, you can find a C/C++ compiler for just about any platform out there, where you can't with C#.
Also linking into 3rd-party libraries, while I'm sure there's a way to leverage them in C#, you'll be able to take advantage of them without interop (Marshaling, etc) in C++.
Edit: one last thing: RELIABLE memory management. Yes you can use dispose(), and try-finally, but there's nothing quite like KNOWING the memory is gone when it's popped off of the stack. Through techniques like RAII, when you use well-constructed classes, you will KNOW when your classes release resources, and not waiting around for the GC to happen.
With P/Invoke there is very little that is impossible in .NET (most obviously device drivers).
There are also things where the advice is to not use .NET (e.g. shell extensions, which get loaded into any process that opens a file dialogue1).
Finally there are things which will be much harder in .NET, if possible at all (e.g. creating a COM component that aggregates the FTM).
1 This can create a problem if that process is already using a different version of .NET. This should be alleviated in the future with .NET 4 having the ability to support side by side instances of the runtime.
I'm not sure if you're talking about language features or applications. My answer though is for applications / components.
Really there are only 2 things you cannot do in C# that you can do in C++.
You cannot use C#, or any other .Net language, to write a component for a system that only accepts native components
You cannot use C#, or any other .Net language, to alter certain properties of a CCW for which the CLR does not allow customization
The most notable item here is Device Drivers. This is a framework that only accepts native components and there is no way to plug in a managed component.
For everything else it's possible to do the same thing in C# as it is in C++. There are just a lot of cases where you simply don't want to and a native solution is better. It's possible for instance to manage and manipulate memory in C# via unsafe code or IntPtr. It's just not nearly as easy and generally there's no reason.
You can't write device drivers for one.
I think there are several important points:
You can do anything in C#/C++/Java/Python/Lisp or almost any other language, finally all of them Turing complete ;)... The question is it suits your needs?
There is one big and extreamly important limitation of C#... It runs only one single platform Windows... (Mono is still not mature enough).
There are many applications where GC is just a waste of resources, applications that can't afford you throw up 1/2 of memory untill next gc cycle: Games, Data Bases, Video auido Processing and many other mission critical applications.
Real Time applications (again games, video processing and so on). Non-deterministic GC makes life much harder for them.
In fact, most of desktop applications: Web Browsers, Word Processors, Desktop Environment itself (like Windows Explorer, KDE or Gnome) are written in compiled languages with careful thinking about resources... Otherwise, they would just be terrible bloated applications.
Whereas writing shell extensions in Windows XP was possible in C# it is next to impossible to write shell extensions for Vista and Windows 7. Shell extensions and Namespace extensions (and anything else that uses the new Properties system) (kindof) must be done in C++ unless you're into pain.
There are two obvious answers:
VC# can never run without the .NET
framework. Native C++ can. That may
be necessary in some areas (others
have mentioned device drivers, but
more common examples might simply be
clients where the .NET framework is
not installed. Perhaps you're
distributing an application and you
know not all of your customers are
willing to install .NET, so your
sales would go up if you made an app
that just worked without the
dependency on .NET. Or perhaps you're
working on some mobile device where
the couple of megabytes taken up by
the .NET CF can not be justified. Or shell extensions where using .NET can cause nasty problem for the user.
And VC# can never use C++ language
features. Native C++ can. (Managed
C++ can too, of course, but that's a
different issue). There are, believe it or not, things that can be done more conveniently or elegantly in C++. And they're only accessible if you're programming in C++.
System calls are no problem, however. p/invoke lets you do those from C#, almost as easily as you could from C++.
inline assembler
You cannot use C++-Libraries with classes (P/Invoke can only be used for functions AFAIK)
You cannot use callbacks with P/Invoke.
Is C# in particular and .NET in general self compiling yet (this is not a troll, I genuinely don't know)? If not, you can use VC++ to write C# and .NET, but you can't use C# to do the same job.
This is tongue in cheek, but it also is an answer to your question... you can screw things up much more severely in VC++ than you can in VC#. Not that you can't manage to screw things up severely in VC#, but in general, you can screw them up easier and more thoroughly in VC++.
Again, kind of tongue in cheek, but also an answer to your question. Perhaps not what you were hoping for, but... :-)
There's also hard real-time applications. Any language with a GC cannot be used, just in case it decides to collect during a time-constrained part of the code. Java was notorious for not even allowing you to try (hence the EULA about not using it for software "intended for use in the design, construction, operation or maintenance of any nuclear facility"
(yes, I know they've since made a modified version of Java for real time systems).
For example, it makes sense to use C++ if it's harder to translate the header files for existing libraries than it is to give up the existing managed libraries.
The Main difference is:
C++ is a core language with which you can build stand-alone programs. These Programs communicate directly with the the operating system and nothing else. C++ compilers exist for more or less all platforms (operating systems).
C# is a language that conforms to the CLS. A program written in C# can not start without a CLI engine (.NET Framework, Mono, etc.). A Program written in C# communicates with the .NET framework AND with the operating system. You have a man in the middle. Like all servicing personal, this man can help but it will cause additional trouble. If you want to port, you have a different man in the middle etc. CLI Implementations do not exist for all platforms.
By my opinion every additional framework is a additional source of problems.
Using SSE instructions seems to be one of these cases. Some .NET runtimes will use some SSE instructions, depending on your code. But in VC++, you can use the SSE intrinsics directly. So, if you're writing a multimedia code, you'd probably want C++. (C++/CLI might work as well, presumably)

Categories