2008年6月16日 星期一

C#引用c++ dll 的方法

以相加為範例


c++程式碼  專案-win32應用程式-dll   注意extern宣告

 


// cppdll.cpp : 定義DLL 應用程式的進入點。

//

 

#include "stdafx.h"

 

 

#ifdef _MANAGED

#pragma managed(push, off)

#endif

 

BOOL APIENTRY DllMain( HMODULE hModule,

                       DWORD  ul_reason_for_call,

                       LPVOID lpReserved

                            )

{

    return TRUE;

}

 

extern "C" __declspec(dllexport) double add(double,double);

double __declspec(dllexport) add(double a,double b)

{

   return a+b;

}

 

#ifdef _MANAGED

#pragma managed(pop)

#endif


 

 

C#程式碼  注意using和DllImport

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

using System.Runtime.InteropServices;

 

namespace rehserh

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        [DllImport("cppdll.dll")]

        public static extern float add(double x, double y);

 

        private void button1_Click(object sender, EventArgs e)

        {

            textBox3.Text = add(Convert.ToDouble(textBox1.Text), Convert.ToDouble(textBox2.Text)).ToString();

        }

    }

}