C#调用c++的动态库dll演练例程

C#调用c++的动态库dll演示例程

1.首先编写c++动态库

extern "C" __declspec(dllexport)
int __stdcall add(int x, int y)
{
	return x + y;
}

C#调用c++的动态库dll演练例程

extern "C" __declspec(dllexport)

extern "C"使得在C++中使用C编译方式成为可能。在“C++”下定义“C”函数,需要加extern “C”关键词。用extern "C"来指明该函数使用C编译方式。输出的“C”函数可以从“C”代码里调用.
使用微软专用的_declspec (dllexport)  
cpp文件在编译为OBJ文件时要对函数进行重新命名,C语言会把函数name重新命名为_name,而C++会重新命名为_name@@decoration,
extern "C"表示用C语言的格式将函数重命名
要输出整个的类,对类使用_declspec(_dllexpot);要输出类的成员函数,则对该函数使用_declspec(_dllexport)


__stdcall 限定修饰符需要添加。不加这个限定符,不能成功调用,不知道为什么??


2.c#调用c++dll库中封装的接口函数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;//

public class DLL
{
    [DllImport("DLLCpp.dll", EntryPoint = "add")]

    public extern static int add(int x, int y);//与dll中一致 
}

namespace DLLTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int ret = DLL.add(2, 3);
            Console.WriteLine(ret);
            Console.ReadKey();           
        }
    }
}

using System.Runtime.InteropServices;

一般用到其中的DllImport,它用来调用windows中一些DLL的函数(Windows API),或调用自己用c++写的DLL中的函数

public class DLL
{
    [DllImport("DLLCpp.dll", EntryPoint = "add")]


    public extern static int add(int x, int y);//与dll中一致 
}

注意:c#如果是64位的环境,c++封装动态库的时候,设置为x64。 32位为什么不能调用,还不清楚?