views:

1179

answers:

3

I have created a dll using command line (csc). Suppose that dll contains Add(int,int) method. Now I want to use that add function in vc++??

How to do this?

Your Help will be Greatly Appreciated.

Here is what I am doing.

vcproj; for this project i have right click and linker section add additional dependencies.added the path where dll resides.

main.cpp

using namespace Test

void main()

{

  demo d;

  d.add(5,5);

}

error namespace Test Does not exist.

How to resolve this?

I need to use that dll as in unmanaged code

+5  A: 

Your C# assembly needs the ComVisible attribute (among a few other things).

[assembly: ComVisible(true)]

There's a guide to doing this here.

Matthew Brindley
If the C++ application is managed, then it's even easier than this of course, and you can avoid COM altogether.
Noldorin
+4  A: 

From MSDN forums Calling C# from unmanaged C++:

What you want to do would be to compile only the files where you want to load the C# code /clr and then call away using C++/CLI. The rest of your app will remain native while those cpp files you compile /clr will be mixed native and CLR. You should be able to just call into your C# library using C++/CLI syntax.

Once you throw /clr on the cl.exe command line for a file, within that file, you can call any managed code that you want, regardless of whether it was written in VB.net, C# or C++/CLI. This is by far the easiest way to do what you want to do (call C# code from your native C++ app), although it does have its caveat's and limitations. By and large though "It Just Works". Also, it's faster than p/invokes.

Dana Holt
+1  A: 

This highly depends on what type of C++ application you are building. If you are building a C++/CLI assembly then you need to make sure the project has a reference to the C# DLL. Once that is done you should be able to type the code as written assumping you have a definition of Demo like so.

namespace Test {
  public class demo {
    public void add(int left, int right) { 
      ...
    }
  }
}

If you are building a normal, non-managed, C++ project then you must use COM interop to access the assembly. This involves making the demo type in your C# project COMVisible and registering it for COM interop. After which you can access it like any other COM component.

JaredPar