I was told by a colleague of mine that Visual Studio allows one to point to a .dll and auto-magically generate a C# wrapper class. Is this really possible? And if so, how does one go about achieving this? I've browsed the web, but have failed to come up with anything!
Thanks all!
Figured I'd share these resources as well,
How to: Create COM Wrappers
And courtesy of #Darin, Consuming Unmanaged DLL Functions
3 cases:
The DLL represents a managed assembly => you directly reference it in your project and use it
The DLL represents a COM object => you could use the tlbimp.exe utility to generate a managed wrapper
The DLL represents an unmanaged library with some exported functions. That's the toughest one. There are no tools. You will have to consult the documentation of the library to know the exported function names and parameters and build managed P/Invoke wrappers. You could use the dumpbin.exe utility to see a list of exported functions. Here's an article on MSDN about the different steps.
This certainly isn't possible with any DLL. Just a very specific kind, one that implements a COM server. The converter needs a good description of the exported types, that's provided for such servers by a type library.
A type library is the exact equivalent to metadata in a managed assembly. While it starts life as a standalone file, a .tlb file, it often gets embedded as a resource in the DLL. Good place for it, keeps the type descriptions close to the code that implements it. Just like the metadata in a .NET assembly.
Some tooling to play with to see type libraries (not sure if it works in Express): in Visual Studio use File + Open + File and pick, say, c:\windows\system32\shell32.dll. You'll see the resources in that DLL, note the TYPELIB node. That's the type library. It is binary so actually reading it isn't practical. For that, run OleView.exe from the Visual Studio Command Prompt. File + View Typelib and select the same DLL. That decompiles the type library back into IDL, the Interface Description Language that was originally used to create the type library. Highly readable, you'll have little trouble understanding the language. And can easily see how the .NET Tlbimp.exe can translate that type library into equivalent C# declarations.
Type libraries are old, they have been around since 1996. Originally designed by the Visual Basic team at Microsoft, as a replacement for VBX, the 16-bit VB extensibility model. They have been very successful, practically any Windows compiler supports them. But they are limited in expressive power, there is no support for things like generics and implementation inheritance. Notable is that the Windows 8 team has replaced type libraries for WinRT. They picked the .NET metadata format.
I know this question is fairly old and seems to have been answered sufficiently, but I just want to add one thought I think might be important.
I could be totally wrong, so please take my answer with a grain of salt and correct me on this if I am.
To be able to call members/fields in a DLL, the information needed to call them must be accessible in some form. That information should be all you need to write a wrapper. With that, you can determine all members/fields "form" aka method headers and so on.
In C# it is possible to load DLLs via reflection and get that information. I dont know about different DLL-Types as described above, but as I said, to call the members/fields this information has to be there in some form. So using reflection to get that Information, you could generate a new class e.g. "prefixOriginalname" and have it have the same members/fields as your original class, calling the members/fields of your original class and adding your desired extra functionality.
So
Every DLL (or peripheral document) gives you the information need to use its types. Namely everything that is implemented as "public"
You can access this needed information via reflection
Given 1. and 2., you can create a program to extract the needed information from DLL and generate wrappers accordingly.
As I said, I am not 100% sure on this one, because the other answers make it sound to me like that might be too difficult or even impossible for some reason.
Related
Attempting to build a C# NPAPI plugin I have found a tutorial which describes that your dll needs to implement a number of methods such as NP_GetEntryPoints , NP_Initialize and NPP_New along with a number of others.
However what I want to understand is if I can simply mirror these method names and construct equivalent datastructures as described in the article (like _NPPluginFuncs) in C# and everything will work?
Could someone please be kind enough to provide some guidance? Is it possible to build a NPAPI plugin in C# and if so what are the basic steps involved?
As stated in the documentation:
A NPAPI browser plugin is, at it’s core, simply a DLL with a few specific entry points
That means you need to export some function from a regular dll, that is done usually in C/C++. Unfortunately it is not possible to expose any entry point from a plain C# dll, but look at this answer, with some effort it appear to be possible to trick some export by some sort of post build tool.
In any case don't expect to pass too much complicated data structures from/to the plugin interfaces, it will be a pain. If you are interested in doing more research the keywork to use is "reverse P/Invoke", in analogy with direct P/Invoke that is calling regular dll from managed world.
The reason a C# dll can't expose directly "entry points" is that entry point are actually just some address inside the dll poiting to some assembly code immediately executable. C# dll are different kind of beast: they are just files containing IL that is compiled "Just In Time" and indeed such compilation is forced AFAIK with some OS tricks. This is the reason reverse P/Invoke is not starightforward at all.
As Georg Fritzsche says in his comment:
NPAPI plugins are basically DLLs with a few required C-exports
and there is no built-in way to export functions (in the C-export sense) from an assembly written in C#.
Some of your options are:
A mixed-mode C++ assembly which can export the functions directly. This could have implications for hosting the CLR in your plugin's host process.
A small native DLL which hosts the exports, then uses COM interop to delegate to a C# assembly containing the plugin functionality. The "official" way to do so-called "reverse p/invoke".
An intriguing project which post-processes your fully-managed assembly, turning static methods marked with a custom attribute into named function exports. (I have no affiliation with this project; I stumbled across it after I got to wondering whether anyone had improved on the COM interop way of doing things.)
I´m really in the need of getting a deeper understanding of how to set up things right to get an elegant interaction between my C++ and C# code bases.
What I want to achieve is an in-game editor written in C# for my game engine (C++/DX). For doing so I let VS build my engine as a C++ dll with some additional functions (unmanaged code) to access the required functionality of my engine from the C# editor code base. So far so good.
The first thing which is bugging me is that I´ve to build the dll with CLR support. Otherwise C# does not accept the dll for some reason. It doesn´t even allow me to add it to the resources ("A reference to 'C:\Users...\frame_work\Test\frame_workd.dll' could not be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component.").
And when I build the dll with CLR support and add it to the references in C# ,re-build without CLR support, start my editor and make a function call from the dll then I get an Exception HRESULT: 0x8007007E. I searched for it but the only thing I found had to do with dependencies but that doesn´t fit to the alert I get when adding the dll to the resources.
The other point is that I always have to switch the configuration type between application (.exe) and dll. in VS C++ depending on whether I want to run my engine directly or from the editor and every time the complete project is build completely new.
So, could someone explain to me how to organize this the right way? And what could be a possible reason why C# wants the dll to be compiled with CLR support?
Thank you guys/girls.
There are two ways to deal with this.
Either you make your C++ code provide an API which has a fully compliant COM object. If the object is COM then C# can directly interop with it. (This is why you can't add it as a reference directly)
However I think what you are really wanting to do will involve a P/Invoke (calling C/C++ native code from C#). This is entirely possible but it's not always easy. You need to deal with conversions between your C++ API and your C#, pointers and you need to be very careful to pin any references that your C++ code writes to in the C# app.
C# code is managed code (runs in the CLR), and can only directly* reference managed assemblies. So of course you're getting an error when you build against a managed assembly, and then sneak in and replace that managed DLL with an (incompatible) unmanaged DLL. You're basically trying to lie to the compiler, and that generally doesn't end well.
If you want your C++ DLL to be accessible from C#, the simplest way to do it is to build it as a managed assembly (i.e., CLR support). Which you're already doing. Just take out the extra step where you replace the working managed DLL with a non-working unmanaged one.
Also:
C++ dll with some additional functions (unmanaged code) to access the required functionality of my engine from the C# editor
That won't help you, because C# can't directly* call unmanaged code. The simplest way to make this work will be to make additional managed classes and methods in your C++ DLL. Then your C# assembly will be able to directly use those managed classes.
* As Spence noted, you can use -indirect- means (P/Invoke and COM) to access unmanaged code from C#. But that will make your life much more complicated than it is now, not to mention how it will complicate your build and deployment. You're already really close to something that should work -- don't add all that extra complexity.
When calling functions with P/Invoke, you don't add the DLL to the C# project resources (or what you probably meant, references, either).
You will add it to the file list in your MSI project, of course.
Is there a way for a Shared Object file written in C and built on Unix to be called from C# P/Invoke?
Or do I need to use Java or something like that?
Mono has the ability to integrate with native libraries from within C# built on top of dlopen(3). You just have to use the DllImport statement with the name of the library (i.e. 'libform.so.5'), then wrap the native code and data types with a friendly C# class that takes care of all the low-level stuff. This page has a good overview with lots of information on how to deal with marshaling pointers and other unsafe types.
Once you've got your wrapper class written, you can just use that without worrying about the fact that it's using a native shared library underneath.
I would say at the least there's likely to be no easy way, especially if you mean C# on Windows. In that case you would need something that would be able to decode the shared object and get to the code in it, sort of a re-implementation of the ABI for GNU/linux. Also, any other libraries would have to be present and usable as well, such as the C runtime library and the like. This would likely be a very significant effort.
As for doing it directly under linux/Mono, see this answer: Calling UNIX and Linux shared object file .so from c# .
You could also try to see if what open office does, http://packages.debian.org/lenny/cli-uno-bridge could be helpful; but this is more of an interface rather than directly linking the two together.
I have a C++ application. This supports users' C++ plugin DLL's, it will dynamically load these DLL's and then be able to create and use the user's types dynamically. These user types derive from base types and interfaces defined in the main application's core library, so I hold user's objects as pointers to the base class and call the user's virtual functions to make their magic happen.
Now I want to extend the plugin DLL's to allow managed DLL's (I care about C# mostly). I want all of the same magic to happen in C# plugin DLL's.
How can I dynamically load these dll's, some how I think win32's LoadLibrary which I am currently using is going to be happy with a managed DLL. I will not have access to these libraries at compile/link time, they come from the user.
After I get the library loaded, unfortunately I suspect COM in my future as the way to call the derived functions. Possibly I could use the CLI/C++ wrapper I have been reading about but I am very inexperienced here and would appreciate any advice or links to appropriate articles.
Another way of doing this would be creating a C++/CLI project that hosts your C# classes and use it as a bridge in your C++ project.
A few more links to this approach:
Connecting c++ and c# code with a c++/cli bridge
.NET to C++ Bridge
The latest link has simple source code for the bridge
What you'd do is basically start up an instance of the CLR in your process.
Have a look at this article on CLR hosting
Here are some slides that describe my solution.
https://docs.google.com/presentation/pub?id=1YoJRGnveh4By7ym4GL19L7OzYOFORZQB6RgJEPVfFb8&start=false&loop=false&delayms=3000
My solution was to have a win32 plugin dll, loaded through normal means (LoadLibrary) that links to mixed C++/CLI dll, which links to pure managed C# code. I allowed calls to happen both ways using A LOT of boiler plate, and a double c++/cli bridge pattern based off of the link given by Padu. Details were fairly complex, but the job of the end API user is very easy and that was my goal. The managed plugin object writer simply derives from an object, and everything just works.
Essentially I made a pattern that provides "mixed mode pseudo inheritance" Now my c# objects derive from a base class in c++.
I see plenty on the web about VSTO and automating excel from c#, but very little to get started on wiring up a c# assembly to make it visible from Excel.
Can someone point me to some very basic info explaining how to create a COM interface, GUIDS, ComVisible etc?
Basically all you need to do is
Make your assembly COM visible using the respective attribute in the project property Assembly version information dialog
For every public class, add the following block (see [1]) of code above the class definition
Register DLL using the regasm.exe tool found in the .NET 2 installation folder
Also, make sure to add a descriptive name to both application name and description in the Assembly version information dialog (they are later used to pick the COM classes).
[1] Block of code to add before class definition:
[ClassInterface(ClassInterfaceType.AutoDual)]
[ProgId("SomeNameHere")]
[ComVisible(true)]
[Guid("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx")]
After that you should be able to use the class like any other normal COM class.
EDIT
It should be noted that I do not have experience with Excel and C# COM classes - I'm using C# together with Microsoft Navision, which works great the way I described above.
There are many books out there that might get you going. "Pro C# 2008" from Wrox has a great chapter on this.
Also, here is a MSDN blog article about COM Visible to Excel.
Rather than go down the COM route, it is considerably easier (and less of an install issue) to use something like ExcelDNA. It allow you to write XLLs in .Net that don't require registering. It is also open-source and very well community supported.