Qt unmanaged C++ class to work with C# .Net - c#

I need some help now. I would love if someone could help we with "transferring" my QT based code to work with my C# application.
Lets say I have this simple QT Class:
class ItShouldWork : public QObject
{
Q_OBJECT
public:
ItShouldWork(QObject* parent = 0) : QObject(parent){}
QString id() const { return objectName(); }
};
Now I want to be able to access this class with Visual Studio C#, I've tried creating an unmanaged dll and access through an wrapper, tried to create an COM component but right now I'm completely stuck so I'm going back to the beginning with this simple class. I've seen that you can use an extern "C" with __declspec(dllexport) like this:
extern "C" __declspec(dllexport) double Subtract(double a, double b)
and then use _dllImport in .net, this works fine with the function above but when adding for example a QString to it it doesn't recognize my dll anymore and a dllNotFoundException is thrown.
Then I thought maybe you need a wrapper of some kind, yeah and how do you do that then..? googled away but nothing to really help me with c++ and qt functions.
A small step by step on how creating a dll and a c-wrapper or creating a COM component dll directly would be awesome, I don't really care how it's done but if you know a way, please help me with a small tutorial? I'm going crazy...

C++/CLI is the way to go, I think.
See: Wrapping unmanaged C++ with C++/CLI - a proper approach
And especially: http://www.delmarlearning.com/companions/content/1592009638/bonus/009638_BonusCh02.pdf
Going into that subject in depth is not easy to do in a forum post. But with some research you should be able to create something useable quite quickly.
C++/CLI takes some getting used to, if you're coming from C/C++. It's a bit more restrictive, especially regarding mixing managed and unmanaged types. But the literature will guide you there.
EDIT:
In response to OP's comment to my answer(also see Comment by Ramhound, Me), here is an example I got here:
Have a look at the content behind the link to see the context of m_impl...
String ^ CSimpleObjectWrapper::ToString(void)
{
wchar_t szStr[100];
HRESULT hr = m_impl->ToString(szStr, ARRAYSIZE(szStr));
if (FAILED(hr))
{
Marshal::ThrowExceptionForHR(hr);
}
// Marshal PWSTR to System::String and return it.
return gcnew String(szStr);
}
EDIT 2:
Also depending on the desired depth/complexity/power of your wrapper, you might think about wrapping your classes in C++/CLI "ref class"es instead of using DllImport.

You can create wrapper on Managed C++. Then you will be able to use managed classes in c#. Check this, it might help you http://msdn.microsoft.com/en-us/library/ms235638.aspx

Take a look at http://doc.qt.nokia.com/4.7-snapshot/activeqt-dotnet.html. It has some information on using ActiveQT, which per the website:
Qt's ActiveX and COM support allows Qt for Windows developers to:
Access and use ActiveX controls and COM objects provided by any
ActiveX server in their Qt applications. Make their Qt applications
available as COM servers, with any number of Qt objects and widgets as
COM objects and ActiveX controls.
The page also has examples on how to integrate with .Net.

Related

How generate a DLL from C program for use in a C# project

I need to use a program made in C for a C# project , and for this I need to generate a DLL in Visual Studio 2013, anyone have any tutorial or know how to do it?
I want make a DLL for a structs and read/write functions in C, cheers guys.
You have to use p/invokes. I think this is very often discussed here. Take a look at: Access a method from a DLL from C# program
DLL is probably overkill for what you are doing. You can just write a C procedure and P/Invoke it using CDecl. The problem is that you need to know a whole lot for this. If you are simply trying to iterate over an array fast for a performance critical section, you are better off using structs in C#, slapping unsafe on your method, and then using pointers and addresses to do what you want to do. Code that looks a whole lot like C/C++ is perfectly legal in C#.
See a reference here: MSDN : Unsafe Pointers
Also fished out a somewhat dated reference showing how to P/Invoke the visual c Runtime printf function as an example. Keep in mind that things get really hard when you need to give a pointer to a function and when you need to read offsets etc. to pass around structs. You'll need to pin anything you pass into the method to stop it from being moved by the garbage collector, which will also have performance implications.
MSDN: CDecl P/Invoke example

Integrating Matlab Coder with c#

I want to integrate MATLAB Coder output with a C# project in Visual Studio 2010. My main idea is:
Create a *.m script in Matlab
Make sure the script is compatible with Matlab Coder.
Generate a C++ shared library (DLL) with Matlab Coder
Integrate with C# using something like this:
//Starts the model execution. May take several minutes
public static class DllHelper
{
[DllImport(#"test.dll",CallingConvention=CallingConvention.Cdecl,EntryPoint = "Run()")]
public static extern int Run();
}
Also, I would like to be able to stop the execution and retrieve some partial results. To do this, I was thinking in two methods: StopExecution and RetrievePartialResults
[DllImport(#"test.dll",CallingConvention=CallingConvention.Cdecl,EntryPoint = "StopExecution ()")]
public static extern int StopExecution ();
[DllImport(#"test.dll",CallingConvention=CallingConvention.Cdecl,EntryPoint = "RetrievePartialResults()")]
public static extern MyResults RetrievePartialResults();
Is it possible to do? If no, is there any alternatives? If yes, where can I find more examples?
I have no idea if your plan works, but MATLAB Builder NE might be an alternative. It directly outputs a .Net dll without those hard limitations to the m-code.
The disadvantage is, that MCR is required on the target machine.
I've done both ways. Formerly, our project was using MATLAB Compiler, but we now switched to Coder, because that avoids the overhead of having to install the runtime (which btw often failed to start inside the process for no apparent reason).
We compile the coder output as an unmanaged C project with a C interface and use a C++/CLR project as a wrapper. This has the advantage that we don't need to manually specify the interface for P/Invoke as the compiler will directly read the header files. The C++/CLR assembly is the linked to the C# project where the code is going to be used. Be aware that this is kind of expensive, so try to avoid calling the matlab code in a tight loop and better move the whole loop into the library if that is possible.
Here's a snippet from the wrapper library (still uses old Managed C++ syntax, but that doesn't matter here)
bool CTurconConnect2::Init()
{
// Call the exported function in the library. Imported using a header file.
turcon_initialize();
// Call one of the matlab functions (in this case, the entry function is manually defined
// in the C library, to have a clean interface)
SetParameters(36.0,400.0,20.0,30.0,15.0,40.0,110.0, 0.0, 100.0);
return true;
}
bool CTurconConnect2::Exit()
{
turcon_terminate();
return true;
}
I think your plan of writing a DLL and calling it from c# seems to be one of the two main ways to go.
The alternative would be to:
use the MATLAB as an automation server from C# using the engine
interface via com automation. This allows you to simultaneously debug
your C# application from both the C# side and the MATLAB side, using
debuggers on each side.
Here are examples for both methods, and even a third alternate method (that seems less recommended).
Integrating MATLAB with C# on File Exchange
I've achieved the exact functionality you're asking about using the MATLAB Compiler. I don't have any experience with the MATLAB Coder, but should be the same principle. Once you have a MATLAB Library compiled, you can access it using P/Invoke in C# like you would with any other unmanaged library (and as you specified in your question).
Theres a couple of caveats:
I think you might have an issue design-wise trying to successfully implement your "stop execution" strategy. The MATLAB executables/libraries are meant to execute from start to finish without much control over the runtime. If you can split your script up into multiple pieces to handle that design, that may work better.
Compiled MATLAB libraries require you to "Start" and "Stop" the MATLAB Component Runtime manually, as well as a component runtime for each script. So, execution flow, would be something like:
StartMCL();
StartScript1_Runtime();
Run_Script1();
StopScript1_Runtime();
StopMCL();
If you attempt to run the "Script 1 Runtime" prior to starting the overall MCL, the app will crash. So, you need to be careful with how you design the wrapper class to handle that properly. Also, you want to be sure to Stop everything before exiting your app, otherwise, the MCR will effectively see 2 "Runs" in a row, and will crash.
You didn't cover any input/output arguments in your question, but in most cases, you will need to use MATLAB functions to create the MEX variables to hand data in/out of the MATLAB environment.
There is a great set of sample source here that should cover all of the above:
http://www.mathworks.com/matlabcentral/fileexchange/12987-integrating-matlab-with-c
Also, the Compiler help itself has a bunch of useful resources.
http://www.mathworks.com/help/compiler/shared-libraries.html
So in a list form,
I doubt that you will be able to stop the matlab code unless you break it up into multiple functions, which you may call as needed.
That you should be able to halt execution by calling on a thread and stopping the thread as you need, or better, send a signal for the thread to stop, which it will abort between functions (for the purpose of partial results)
That matlab is a terrible language for fulfilling the requirements on item 1 (not that I have ever had any good experiences with it myself)

How to utilise C# methods in a different programming language

I am attempting to connect to a commercial server application, which only has a C# API.
I would imagine that the best approach for doing so would be to create a C# DLL - which is what I have done. However, when examining the methods contained within the DLL utilising 3rd party tools, the methods do not seem to be visible.
I have searched extensively on StackOverflow, and found that the following suggestion works for most people - however the methods are still not visible when utilising this extension.
Thus it may be time to seek an alternate approach to how this problem can be solved - one option could be a C# console application.
Any ideas regarding what would be the best approach?
EDIT:
After running the DUMPBIN program, this is the output:
C:\Program Files (x86)\Microsoft Visual Studio 11.0>dumpbin /EXPORTS "C:\Users\mark\Desktop\Test.dll"
Dump of file C:\Users\mark\Desktop\Test.dll
File Type: DLL
Summary
2000 .reloc
2000 .rsrc
2000 .text
If the Basic+ has an option to call C code, you have an option to create a project in Managed C++:
Exports some function decorated like:
extern "C"{
__declspec(dllexport) void _cdecl MyFunction()
{
_MyImpl(); //see below wy this
}
}
void MyImpl()
{
MyCSharpObj^ test = gcnew MyCSharpObj()...
test->Methods(...
}
Outside of the portion decorated with extern C you can safely call and mix managed and unmanaged calls. The reason you should go outside the extern C block is that almost all managed function have overloads, and Extern C does not support method overloading even in call.
You can call c# by just adding references ( actually you can write all your code in managed C++, but is not so friendly ) to your .NET libraries.
Basic+ seems to be made by Revelation Software.
On this page, it says:
OpenInsight 9.1 released
This new OpenInsight release included a
couple of .NET innovations. NetOI enables developers to code using
their Microsoft Visual Studio licenses and work against an OpenInsight
database. The RevDotNet functionality provides a method of calling
.NET APIs and using the .NET controls within an OpenInsight
application.
Can you use RevDotNet to call your C# APIs directly?

Use C++ class from C#

Alright so I have this C++ image capturing class. I was wondering if I could get some help..I know basic C++ (I have done one intro to c and one intro to c++ class) and I have NO idea how to do this:
I need to use this class (ie create a new c++ project in my solution) and use c# to reference it and use it to save a screenshot of the screen.
When I try to add a new project I dont know which one to choose (win32, mfc, atl, clr, abc, xyz, and so on) .
The image capturing class is here:
http://pastebin.com/m72414ab
I don't know if I need to create .h files or just a .cpp file would do.. like honestly I have no clue where to start lol. I am looking for a solution, but i want to learn in the process so I dont have to ask next time (not to mention that I like c++ so I am gonna continue coding with it)
You cannot easily use C++ classes from C# without knowing some somewhat specialized information about C++/CLI - either rewrite your C++ class in C and use P/Invoke, or find a fully C# solution.
But I'd like to use this c++ class for speed and memory.
I question this, unless you are capturing images thousands of times a second, there's no way choosing C++ would be of any benefit, and it makes your program much more complicated. Stick with C# until you know you need the slight performance boost.
.NET version 2.0 and above include a CopyFromScreen method on the Graphics object. You can create an image, obtain a drawing surface (Graphics) for that, and then copy from the screen into the image.
A quick bit of Googling produced a simple tutorial which demonstrates this using Visual Basic .NET, although it's trivial to port to C#.
This solution results in the same GDI+ calls that your C++ version uses, with the benefit of not having to link in external C++ code (which, as mentioned above, is not straightforward).
It is definitely possible to use C++ constructs from C#, but it does require some dirty tricks. If I remember correctly, last time I tried to do this I used a Managed C++ layer between C++ and C#, and I think this is the most common way to do it. This method worked well, but indeed was unnecessarily complicated.

Call C++ code from a C# application or port it?

I've recently been wrestling with an algorithm which was badly implemented (i.e. the developer was pulled off onto another project and failed to adequately document what he'd done) in C#.
I've found an alternative (from numerical recipes) which works but is written in C++. So I'm thinking probably the safest way to get something working would be to wrap the C++ up in a DLL.
Bearing in mind that I'm still a bit green when it comes to C# and have never tried making a DLL from scratch, does this sound like a reasonable approach (and if so, has anyone tried this / got any advice)? Or should I go the whole hog and try and port the C++ routine into C#?
Edit - I'm not looking for anyone to make the decision for me, but if anyone has any exprience of either route I'd be interested to hear their opinions and any nasty pitfalls that should be avoided. For example, how nasty is passing in lists of data from C# to a C++ STL vector?
I tried linking to c-dll's from c# code with quite good results, even though I had some problems sending data between the environments. Otherwise the procedure is quite straight forward. The more data you send back and forth (both amount and frequency) the slower your program will run, but you have probably already figured this out on your own.
The main drawback was maintaining the c#-c glue code (interface code) each time something changed or someone found a bug.
Here is a bit of code to get you started:
using System.Runtime.InteropServices;
class myDllCaller {
//call to function in the dll returning an int
[DllImport("MyFavorite.dll")]
private static extern int dllFunction(//list of parameters to function);
public static void Main() {
int rerult = dllFunction();
}
}
If the C# version Mitch references isn't of a suitable licence for your purposes, You could use a managed C++ wrapper, that could reuse, and wrap the C code you have, but still be visible to your managed applications as a native .Net assembly. I've used this approach in the past for using the C API of a library that didn't have its own native .Net API, and found it relatively painless marshalling data between the two.
It depends what your goals are.
If it's to have a working application I'd weigh-up the costs and benefits of both approaches and go with the most cost effective.
If it's to improve your C# then by all means rewrite the C.
...Or you could download the already implemented code in C# from here.

Categories

Resources