Calling C++ Unmanaged Class from C#

原创 2005年04月30日 11:36:00
This may be a no-brainer, but I thought I'd post it anyway.

If you have a C++ class in an unmanaged dll what is the best way to call it from C#?

1. You need to wrap the C++ class in a COM object or expose the class through dll exports. Managed code can call methods on COM object through COM Interop. And it can call dll exports through P/Invoke.

2. There is another way to do this using P/Invoke. Here is the sample code from the SDK.
The best way to do this is to write a thin wrapper in MC++ around your MFC classes and expose managed interfaces from it to your C# code. If you can use Whidbey, you could even compile your MC++ wrapper and rest of the C# code in same DLL using new linker.
// ClassMethods.cs
using System;
using System.Text;
using System.Runtime.InteropServices;
public class LibWrap
    class PINVOKELIB_API CTestClass
            CTestClass( void );
            int DoSomething( int i );
            int m_member;
    [ DllImport( "..//LIB//PinvokeLib.dll",
    CallingConvention=CallingConvention.ThisCall )]
    public static extern int TestThisCalling( IntPtr ths, int i );
    // CTestClass* CreateTestClass();
    [DllImport( "..//LIB//PinvokeLib.dll" )]
    public static extern IntPtr CreateTestClass();
    // void DeleteTestClass( CTestClass* instance )
    [ DllImport( "..//LIB//PinvokeLib.dll" )]
    public static extern void DeleteTestClass( IntPtr instance );
public class App
    public static void Main()
        IntPtr instancePtr = LibWrap.CreateTestClass();
        int res = LibWrap.TestThisCalling( instancePtr, 9 );
        Console.WriteLine( "/nResult: {0} /n", res );
        LibWrap.DeleteTestClass( instancePtr );


Calling C# Methods From C++

In the previous article, I have demonstrated how to call C/C++ libraries from C#. In this post, I w...

Calling Java Class Methods from C with JNI

  • 2017年11月12日 14:06
  • 119KB
  • 下载

Sinking events from managed code in unmanaged C++

Download source code - 7.89 KB Introduction As time goes by, some parts of the big project I am ...

Calling JavaScript in a WebBrowser control from C#

Calling JavaScript in a WebBrowser control from C# Embedding a WebBrowser control in a C# appli...
  • ghlfllz
  • ghlfllz
  • 2011年12月08日 11:17
  • 868

Calling C and C++ from IDL (三) ——数组传递


Calling Fortran function and subroutines from a C or C++ function

在main() 主函数中调用fortran 定义的子函数; 基本思想:将fortran定义的函数,在C++函数中采用C接口重新声明为全局函数;为避免C++中函数的重载,通常在声明函数时常使用C的命令...

Calling C++ Functions From Lua(lua调用c/c++)

Calling C++ Functions From Lua My second tutorial dealt with calling Lua functions from C++. Th...
  • chlaws
  • chlaws
  • 2012年12月25日 15:12
  • 1404

Finding where unmanaged exceptions came from


C#learning class from mountains

  • 2009年09月16日 10:52
  • 10.31MB
  • 下载

Calling Win32 API Routines from HLA

  • 2009年12月08日 21:12
  • 65KB
  • 下载
您举报文章:Calling C++ Unmanaged Class from C#