编译生成C++导出函数dll,并在C#工程中测试

编译生成过程:

1.建立dll工程

选择新建visual C++的

 

这两个类型工程,都会出现下面界面,在这里设置生成dll:

2.设置项目:

项目属性中设置:

 

3.相关代码:

由于项目的名称是"TestCPPDLL",因此,会自动生成TestCPPDLL.h和TestCPPDLL.cpp两个文件,.h文件是要导出内容的声明文件,为了能清楚的说明问题,我们将TestCPPDLL.h和TestCPPDLL.cpp两个文件中的所有内容都删除,然后在TestCPPDLL.h中添加如下内容:

头文件:

#define TESTCPPDLL_API __declspec(dllexport)
EXTERN_C TESTCPPDLL_API int __stdcall Add(int a, int b);

源文件:

TESTCPPDLL_API int __stdcall Add(int a, int b)
{
    return a + b;
}

 

测试过程如下:

新建一个C#空工程项目,修改生成的main文件:

1.添加

using System.Runtime.InteropServices;

2.在静态方法中添加:

[DllImport(@"G:/VS13_Project/TestCPPDLL/Release/TestCPPDLL.dll", EntryPoint = "Add")]
extern static int Add(int a, int b);

具体如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Runtime.InteropServices; //加上这行

namespace testC
{
    class Program
    {
        [DllImport(@"G:/VS13_Project/TestCPPDLL/Release/TestCPPDLL.dll", EntryPoint = "Add")]
        extern static int Add(int a, int b);
        static void Main(string[] args)
        {
            int c = Add(1, 2);
            Console.Write(c);
            Console.Read();
        }
    }
}

 参考:http://jingyan.baidu.com/article/67508eb43f91869cca1ce49c.html

posted @ 2017-09-16 11:30  懒猫的新窝  阅读(738)  评论(0编辑  收藏  举报