I've done a bit of research around this before posting but I couldn't find a direct answer specific to my environment.
I have a third party library written in C++. I have access to the .dll, .lib and .h headers of the library.
I'd like to wrap the library for use in C# using p/invoke. I'd like to know what options I have in terms of doing this and maintaining it. My hope here is that with the .h headers I can utilize some application to automatically provide the wrapper code.
I'm interested in all kinds of solutions including commercial software solutions and any pitfalls of trying to automatically manage the wrapper code.
You could try SWIG which is free. You may be able to script it to run automatically as part of a build process.
Personally I'd just write some wrappers using [DllImport]. Do you really need to access everything in the C++ library from C#? Often I've found you really only need to call a few functions, and the simplicity of dllimport is great
My hope here is that with the .h headers I can utilize some application to automatically provide the wrapper code.
It would be lovely if this were possible, but it is not. It is not possible because the header file does not contain enough information to determine how to marshal parameters. For instance, consider this declaration:
void foo(int *x);
What is x? Its type is int*, pointer to int. But is it a pointer to a single int value, or is it an array of int? You simply cannot tell from the header file. You need to read the documentation.
And what about data flow. Is the information flowing into the native code, or out of it, or in both directions? Again, that detail cannot be expressed a header file.
Now, there are various annotation conventions that can help with this. Essentially these are macros that evaluate to nothing that can be read by a tool and so help with conversion. You see Win32 API functions annotated with _In_, _In_Opt_, etc. These can help, but only the very simplest of libraries can be automatically translated into p/invoke declarations.
Now, if you are prepared to add extra annotation to the raw header files then you might have a chance. It is certainly possible that existing tools exist that will do a good job so long as you express the missing information in comments or macros. SWIG is certainly worth a look, and there are other tools.
The fundamental point of my answer is to try to get across the idea that such translations are not as automatic as you might hope. Personally, I always end up writing my p/invoke declarations by hand. This allows me to get them exactly the way I want, and maintenance is not really a big deal because DLL interfaces typically don't change. They don't change because you don't want to break binary compatibility.
Related
I found here at 6.16 example on user defined complex number class, yet I see no samples on how default C++ complex numbers are brought into other languages via SWIG, is there any sample, is there any requirement alike use of some %include "std_complex.i" inside my .i file?
The usual procedure is described in section 8.4 of the SWIG development documentation. As you can see from the table, it depends on the chosen language, to which parts of the C++ standard library the referring library modules provide access to, so far. SWIG support for the STL still continues to grow.
So the C++ <complex> library may or may not be supported for your target language. Concerning C#, there is no std_complex.i file inside the swigwin-2.0.10\Lib\csharp folder, hence no support.
Of course you could wrap it yourself by hand, but I guess that was not what your question aimed at. In the case of <complex> it also doesn't seem worth the effort, at least for me.
I'm working on a C# project at the moment and I have zero experience with C#.
We have a set of DLLs written in C++, they have the same classes and same functionality, but they work differently. As an instance let's say our program converts BMP files. We have DLLs for converting BMP to JPG, BMP to PNG and so forth.
Our program which is written in C# somehow should wrap those DLLs, but not in a static way. We'd like to be able to change the DLL in use during runtime, and add new DLLs when need be (also during runtime). Like plugins, if you will.
What would your suggestion be to implement this approach?
This looks good: http://blogs.msdn.com/b/jonathanswift/archive/2006/10/03/dynamically-calling-an-unmanaged-dll-from-.net-_2800_c_23002900_.aspx
If you don't know what all of your DLLs are ahead of time, you will probably need to call the Win32 function "LoadLibrary" "GetProcAddress" and "FreeLibrary." As far as I know, c# does not have a way to do a sort of Dynamic PInvoke automatically. See this blog post for more info
Alternatively, you could create a C# wrapper for each of your DLLs using PInvoke and then use managed delegates to call the functions. Then, by changing the delegate, you can call a different function (presumably in a different DLL) at runtime. This would depend on you having a complete list of the DLLs you intend to use at compile time. It is quite a bit more robust than the first option though. It's also a thousand times easier to let the runtime handle all of the marshaling for you. See this MSDN article for more information.
If they are already in C++, I would opt to write the managed assembly in C++.
This walkthrough could be a starting point. Especially the C++ guy does not need to learn C#.P/Invoke is a little bit slower, but the deeper issue is for you the version management as P/Invoke will lead to runtime-exceptions and not compile errors in case of changes.
You could use extern and DLLImport like facilities provided by Microsoft, For more details Go here or Here
We're integrating a communications company's software into our own for doing things like answering calls, transfering calls, matching numbers with clients etc.
They have given us the API documentation, which includes a TLB file. We've used the tlbimp tool to create an assembly which we now want to use in our implementation.
Some of the classes created by tlbimp have been given internal constructors, rendering them uninstantiable. I think it should be ok in this instance as another class should return an instance of these classes.
This made me think though: are there any other pitfalls I should be aware of when using tlbimp.exe, and TLB's as a whole? Would it be better to create the DllImport/ComImport/PInvoke code by hand?
In general if you have a TLB I would at least start my work by consuming the assembly produced by tlbimp.
The tool itself is widely used and produces correct code based on the definitions provided in the TLB. I have seen some circumstances where the resulting code was incorrect but it almost always came back to either a very complex marshalling situation with arrays or a place where the TLB author had simply added the wrong COM annotations.
If you do find any issues down the road then you should consider beginning to hand code the fixes. But I certainly wouldn't start that way.
You cannot pinvoke the kind of COM interface methods that are declared in a type library. The DLL that implements the COM server doesn't export the methods. You can use late binding with reflection or the dynamic keyword but that's painful and error prone. Use the import library, that's why it is there.
I need to create a VC++ wrapper in C#. Is there a way to automatically generate the code?
Edit: let me clarify a bit: I have a simple project with complicated math functions (computing magnetic declination) in c++. Its just three files, one header, one command line controller and the library.
I was looking at SWiG but I found it to be enigmatic :P. I'm taking a look at C++/CLI.
Any tips and pitfalls to watch for?
Take a look at: Using Unmanaged C++ Libraries (DLLs) in .NET Applications
Or you can use C++/CLI
SWiG supports C#. But a C++/CLI wrapper will be much more ".NET-like" than one automatically generated by SWiG.
You can have a look at this tutorial:
http://www.codeguru.com/csharp/csharp/cs_data/article.php/c4217
I think it's better if you make your own wrapper than using any tool (if it does exists). The reason is that you can create a better C# wrapper using the right philosophies instead of generating a list of function call from a DLL.
And for the pitfalls, the only thing I can say is that since you are going to mix manage and unmanaged class, be sure that your struct/parameters are matching (sizeof or types).
As for most short questions: It depends on your settings and requirements! ;-) If you have a more C style interface, you might be able to solve your problem just by using Interop. If "real" OO progamming and C++ are involved, you probably have to look at C++/CLI. That can be easy, but it can also become painful - depending on your classes. As far as I know, there's not automatic code generation tool.
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.