开发者

How to access a C++ Class in a C# code?

开发者 https://www.devze.com 2023-03-22 21:15 出处:网络
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.

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.


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#.


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.


Google P/Invoke or see www.pinvoke.net


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号