Adding .cpp files (C++ code) into C# 2.0 application

  • Thread starter Thread starter eljainc
  • Start date Start date
E

eljainc

Hello,

I have 3 or 4 source code files that were written in VC++ (an earlier
version, like VC++ 6.0). I need to be able to use the code in my
C# .NET 2.0 forms program. I have tried to add existing items
(the .CPP files) to a new VC# project. How do I go about accessing the
methods and variables in those .CPP files. I have read about creating
a wrapper DLL for the CPP files so that unmanaged C++ code can be
accessed. However I have yet to find a good tutorial or explanation on
how to create the DLL file from the original .CPP/H files. I have
tried to make a class in a VC++ project, but I cannot provide the
necessary "glue" to get the functions/methods accessible.

Thanks for any help.
Mike
 
Hi Mike -

I don't have any answers, in large part because I asked almost the
identical question (see thread subject "How do I call C++ functions
from a C# coded Service?", with luck we should get something on one
(or perhaps both) of these threads.

Happy Coding
cg
 
eljainc said:
I have 3 or 4 source code files that were written in VC++ (an earlier
version, like VC++ 6.0). I need to be able to use the code in my
C# .NET 2.0 forms program.

You can write a C++/CLI wrapper around it.

class Unmanaged
{
public:
void Execute() { }
};

public ref class Managed
{
public:
Managed() : pimpl(new Unmanaged) { }
~Managed() { delete pimpl; } // Dispose()
!Managed() { delete pimpl; } // finalizer
void Execute() { pimpl->Execute(); } // thunk
private:
Unmanaged * ptr;
};

Compile this as a .NET class library. Then you can use it from C#:

using(Managed managed = new Managed())
{
managed.Execute();
}

Of course it gets more complicated if you have callbacks, arrays to be
marshaled, complex inheritance hierarchies, etc. But this should point
you to the right direction.

Forget about VC6 and compile it with VC++ 2008.

Note that Managed is IDisposable now, you must call Dispose on it in
..NET (using in C# does that automatically).

Tom
 
Back
Top