3

I have following problem statement.

  • Export a C++ class in the dll (un-managed).
  • Create and use an object of this class in C# code. For the first part I have the classDLL.h as follows

``

#include <iostream> __declspec(dllexport) class pABC{ private: int x; public: void func(); }; 

The respective cpp is also there. On compiling I get the dll.For thesecond part of the problem I am not getting how to proceed.

Thanks.

2
  • 1
    Duplicate of stackoverflow.com/questions/315051/… Commented Jul 25, 2011 at 9:21
  • @unkulunkulu: That question is quite old, and doesn't mention C++/CLI as an option. Commented Jul 25, 2011 at 9:26

4 Answers 4

4

You can't access an unmanaged class directly from C# code. You can write a small wrapper .DLL in C++/CLI, which wraps the unmanaged class in a managed class which is visible to C#.

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

1 Comment

What I did when I had this issue. Worked without a hitch for simple things.
3

Convert the C++ class and DLL to be COM. If you don't have access to the unmanaged code source or can't modify, you can implement a COM wrapper class in a different DLL that consumes the original DLL and proxies the functionality of the original class through a COM class.

Define an interface in an IDL file to represent your C++ class (along with a coclass declaration). Use only basic COM types in all methods (BSTR for strings, HRESULT for return codes). Complicated structs passed as params should be refactored into their own interface.

Build your COM DLL such that it outputs a type library (tlb file).

Implement the interface (including IUnknown methods) in your C++ class. Build the COM DLL and register it.

Import the type library into your C# project. Or use the type library importer. You should now be able to instantiate your C++ class (through COM) via "new".

By the way, ATL is a great framework to get going on this quickly.

Comments

1

Google P/Invoke or see www.pinvoke.net

Comments

0
 [DllImport("pABC.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern void func(); 

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.