C#引用C++开发的DLL

C#语言使用方便,入门门槛较代,上手容易,并且语法与C,java有很类似的地方,IDE做的也好,通用性好,是MS下一代开发的主要力量.但是其开源代码较少,类库不是十分完美,在架构方面还有一些需要做的工作.

C++写的程序占用内存较小,直接对内存或者文件操作,因此一些关键的步骤或者一些最内层的循环在一定程序上还需要依赖C++.

 下面我做一些简单的例子

 C++编写DLL

QpHelper.h

#pragma once
class QpHelper
{
public:
    // Returns a + b
    // 设置为导出函数,并采用C风格。函数前加extern "C" __declspec(dllexport)
    // 定义函数在退出前自己清空堆栈,在函数前加__stdcall。
    static __declspec(dllexport) int __stdcall add(int a, int b);

    // Returns a - b
    static __declspec(dllexport) int __stdcall sub(int a, int b);
};

QpHelper.cpp

#include "QpHelper.h"

int QpHelper::add(int a, int b)
{
    return (a + b);
}

int QpHelper::sub(int a, int b)
{
    return (a - b);
}

extern "C" __declspec(dllexport) int Add(int a, int b)
{

    return a + b;
}

 C++调用C++ DLL

 Test.cpp

// Test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "QpHelper.h"
#include <iostream>
using namespace std;

// 静态方式调用DLL
#pragma comment(lib,"MyDllDemo.lib")

int main()
{
    QpHelper qpHelper;

    int result = qpHelper.add(4, 5);

    cout << qpHelper.add(4, 5) << endl;

    cout << qpHelper.sub(4, 5) << endl;

    return 0;
}

运行效果:

C#调用C++ DLL

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {

        [DllImport("MyDllDemo.dll", EntryPoint = "Add", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
        public static extern int Add(int a, int b); //DllImport请参照MSDN

        static void Main(string[] args)
        {
            Console.WriteLine(Add(1, 2));
            Console.Read();
        }
    }
}

运行效果:

posted @ 2016-04-21 13:31  Bobby0322  阅读(3015)  评论(0编辑  收藏  举报