Link to home
Start Free TrialLog in
Avatar of parabellum
parabellum

asked on

Using c++ lib file in c#

Hello,

I have a lib file written in unmanaged c++. (I have access to the source code.)

How can i use it in c# ?
I think that i need to write a wrapper and convert it to a managed dll.
But i don't know where to start.

Can you please show me a working example source code or good links ?
thanks.


ASKER CERTIFIED SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

Suppose you are having the unmanged library called TestLib.dll
Then Your managed code should be as shown below...

using System;
using System.Runtime.InteropServices;    
class Consume
{
    [DllImport("TestLib.dll")]
    public static extern void Hello ();

    static void Main ()
    {
                Hello ();
    }
}
>>ManagedCode.fooWrapper.foo();

How does the C# assembly know the ManagedCode namespace in that example?  I'm guessing it works but I don't know whats happening in the background and I'm interested :)
>> How does the C# assembly know the ManagedCode namespace in that example?

The assembly just needs to be referenced by the C# code (just like any assembly) and that's it. Once a .Net assembly is referenced it is visible globally, unlike unmanaged C++ there things have to be declared.