locked
How to Load C++ Dll

    Question

  • I have made a C++ dll, its complete source code is following

    #include <windows.h>

    #include <stdio.h>

     

    #if BUILDING_DLL

    # define DLLIMPORT __declspec (dllexport)

    #else

    # define DLLIMPORT __declspec (dllimport)

    #endif

     

     

    class DLLIMPORT DllClass

    {

      public:

        int add(int ,int );

     

    };

     

     

    int DllClass::add(int a,int b)

    {

        return a+b;

    }

     

     

     

     

    BOOL APIENTRY

    DllMain (

      HINSTANCE hInst     /* Library instance handle. */ ,

      DWORD reason        /* Reason this function is being called. */ ,

      LPVOID reserved     /* Not used. */ )

    {

        switch (reason)

        {

          case DLL_PROCESS_ATTACH:

            break;

     

          case DLL_PROCESS_DETACH:

            break;

     

          case DLL_THREAD_ATTACH:

            break;

     

          case DLL_THREAD_DETACH:

            break;

        }

      

        return TRUE;

    }

    you people can test my given dll code using Dev C++.

                      

    Following is C# Code, where I tried to call C++ dll like C dll

     

    namespace dlltest

    {

        public partial class Form1 : Form

        {

            public Form1()

            {

                InitializeComponent();

            }

            [DllImport("c:/Project1s.dll")]

            public static extern class DllClass;

      

            private void button1_Click(object sender, EventArgs e)

            {

               DllClass obj = new DllClass();

               MessageBox.Show(obj.add(2+3).ToString());

            }

        }

    }

     

    when I compiled above C# code I got following errors

     

    Error    1            { expected            c:\dlltest\Form1.cs       

     

    Error    2            Invalid token ';' in class, struct, or interface member declaration        C:\dlltest\Form1.cs

    Error    3            } expected            c:\dlltest\Form1.cs

               

    Error    4            The modifier 'extern' is not valid for this item  C:\dlltest\Form1.cs     

     

    Please write complete code that how can i get red of the above error.

     

                              Thanks 

    Monday, March 13, 2006 2:35 PM

Answers

  • You apply this attribute to methods and not to classes. You can read about the DllImport attribute here.

    If you need to use classes you probably have to look into writting a managed wrapper in mixed mode C++.

    Tuesday, March 14, 2006 12:48 PM