C# – Using a C++ dll in C#

cdll

I'm attempting to consume a dll written in C++ from a C# application. I have 3rd party source code for the C++ dll (the Cyclone physics engine) and do not want to manually port it over to C#.

In the C++ project
I changed it to output a dll. I changed it to use the /clr flag. I changed it to use Multi-threaded Debug DLL (/MDd) because that was the only one compatible with /clr and also compiled.

In the C# project
I added a reference to the dll. I'm using the cyclone namespace.

At first there was absolutely nothing under the namespace. I think this is because in the C++ code, all classes were declared with no access modifiers and the default is private. So for the class "Particle" I changed the definition to:

public class Particle
{
//...
}

Now I can successfully declare a variable of type Particle from the C# code. However, intellesense and the object browser report Particle to be a struct (?) and it doesn't contain any methods at all. The c++ code declares a bunch of methods after "public:" access modifiers so I don't know what the problem is.

For example,

public:
void integrate(real duration);

What am I doing wrong?

Best Answer

The Particle class is not a managed class, hence it is treated as a struct. You need to use the ref keyword to make it managed and garbage collected. You also need to do the same to every other class that references it which might be a problem. The best solution I think, is to create a managed wrapper class that uses the Particle class internally. This wrapper class can then be referenced by .net.

See here: