create C++ DLL to be used by C# ?


  • I want to write a native C++ function that I can later access from C#.

    Please keep in mind I do not have much experience developing on windows, (mostly unix) and that my only windows compiler is VS2005.

    I tried creating a MFC DLL.  I am able to access this from a C++ .net program, but not from a C# program using P/Invoke.  It seems that a plain MFC DLL is not "good enough" for use with DllImport.  Is this correct?

    It seems that I have two options:

      1) compile the C++ function as a COM DLL (not sure how to do this from VS2005 - I don't see an option for that).  I see an option for an ActiveX DLL...I hope I don't need to do that.

     2) write a C++ .net wrapper class, create a .net assembly, and use that assembly from C#.

    I would prefer option do I create a DLL that C# can use via [DllImport] ?

    Tuesday, June 13, 2006 8:35 PM


All replies

  • I suspect that ActiveX means COM, ActiveX was the initial name for COM.


    Tuesday, June 13, 2006 10:05 PM
  • It is a matter of opinion but COM interop in C++ always struck me as a "keep the boss happy" option.  Either write it in straight C++ and use the DllImport attribute or write it in C++/CLI (ref class, "hat" and all that) and create a native .NET assembly.

    Tuesday, June 13, 2006 10:15 PM
  • I would tend to agree.  While you asked for the COM option as a preference, it's really much better to just compile it as C++/CLI code, you need the .NET framework anyhow, and it's much more flexible to work with it that way.


    Tuesday, June 13, 2006 10:17 PM
  • hello ,

     just  write one pure win32 dll  . and just pass parameter as void * . it works

    remember when u pass string or character values it is 2 byte in c# and in mfc it is 1 byte. U have to do the conversion


    Wednesday, June 14, 2006 6:50 AM
  • I have created a simple win32 dll that I can access from C++ in VS2005.

    My question was, what do I need to do to access it from C# ?  Simply using P/Invoke does not work.

    Another suggestion was just to write a C++ .net dll, and call that from C#.  I will try this, but I have a hard time believing this will be as fast as native code (I am porting some image processing routines from a unix environment).   Once I have created a .net dll from c++, it looks like I need to do these steps:

    1. create a "strong name" with the sn utility
    2. run gacutil

    Is this correct?  I can't simply link against the .net DLL?
    Wednesday, June 14, 2006 10:53 AM
  • Once it's a .NET dll, you just need to add a reference to it in your project.


    Wednesday, June 14, 2006 10:55 AM
  • "Simply using P/Invoke does not work".   Why not, what goes wrong?  What is the declaration of the C++ function?

    Wednesday, June 14, 2006 2:29 PM
  • Rick, also take a look at your previous post at

    Ayman Shoukry
    VC++ Team
    Wednesday, June 14, 2006 4:04 PM