6

I need to access code in a native C++ DLL in some C# code but am having issues figuring out the marshaling. I've done this before with code that was straight C, but seem to have found that it's not directly possible with C++ classes. Made even more complicated by the fact that many of the classes contain virtual or inline functions. I even tried passing the headers through the PInvoke Interop Assistant, but it would choke on just about everything and not really no what to do... I'm guessing because it's not really supported.

So how, if at all possible, can you use a native C++ class DLL from .NET code. If I have to use some intermediary (CLR C++?) that's fine.

2 Answers 2

11

There is really no easy way to do this in C# - I'd recommend making a simple wrapper layer in C++/CLI that exposes the C++ classes as .NET classes.

It is possible to use P/Invoke and lots of cleverness to call C++ virtual methods, but I wouldn't go this route unless you really had no other choice.

Sign up to request clarification or add additional context in comments.

1 Comment

Very good answer. Better than strictly solving the question ("How to marshall...?") is solving the actual need of the OP.
0

You might have a look at SWIG, if nothing else just to see how they handle the basic wrapper code (which SWIG generates). I know next to nothing about C# native code bindings so I can't judge if their approach is sound, but they do a decent job with some of the other language bindings.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.