views:

26

answers:

1

I've been browsing the web for over 48 hours reading up on interoperability and playing around with Pinvoke and C++/Cli (very limited the latter). There is an unmanaged c++ api (a namespace containing a lot of exported structs which contain methods, all pure virtual and implemented across several cpp files as classes and what not) and I would like to call into them from .NET. I do not really have access to the source code, only to the resulting dll and so It seems c++/cli would not work. But on the other hand, I have not been able to find examples, tutorials, or documentation of using Pinvoke for non c-style like apis which have namespace and structs and classes containing methods. I believe if they are exposed, the dll SHOULD contain entrypoints albeit mangled up in name...is my only choice without source code access then to do this? And if I may also ask..supposing i had access to the source code, what would be the most non-intrusive way (i.e. requiring the least modification if any) to wrap the api for .net use?

Thanks

A: 

If you have the header (or can make one from the documentation) you should be able to write a C++/CLI wrapper. It's just C++. Ideally there would also be a convenience lib, then you could just include the header link to the lib.

Your C++/CLI code would be simple wrappers around the unmanaged classes, something like:

public ref class Foo
{
  private:
     NativeFoo f;
  public:
    int method1(int i) {return f.method1(int i);}
// etc
};

[disclaimer: I'm typing code into the answer box. Possible typos I suppose.]

You build that, your C# code adds a reference to the resulting assembly, then in your C# code you just use Foo as the managed type that it is.

This is going to be a lot easier than figuring out mangled names. Yes?

Kate Gregory
I suppose it is (except for the complex inheritance and very complex data-types). I came across this example http://www.codeproject.com/KB/mcpp/usingcppdll.aspx it seems to propose a mix between creating an unmanaged wrapper (to preserve behavior) and pinvoke and then a cli wrapper. That sounds like a lot of work for a large complex library. pinvoke, even with mangled names does not appear to be an option because classes have state and member methods and are not procedural c functions...a cli wrapper is the least i would have to do am i right?
Palace
You would not pinvoke from a C++/CLI wrapper unless you had some really strange marshaling needs. The good thing about C++/CLI is that it understands your unmanaged types, inheritance and all. Ideally you don't need to expose all that to the managed side and you have some sort of Facade pattern so what you show the managed side is TakeCareOfIt() and the complexity is inside. My example in the answer just exposed one-for-one, you will make a choice depending on your system's needs.
Kate Gregory