vs2010 创建和C#使用动态链接库(dll)

一、VS 用 C++ 创建动态链接库


Step 1:创建Win32 Console Application

本例中我们创建一个叫做“Test”的Solution。



Step 2:将Application Type设定为DLL

在接下来的 Win32 Application Wizard 的 Application Settings 中,将 Application type 从 Console application 改为 DLL:



Step 3:将方法暴露给DLL接口

现在在这个Solution中,目录和文件结构是这样的:



编辑 Test.cpp 如下:

<span style="font-size:14px;">#include "stdafx.h"    
extern "C"  
{  
    _declspec(dllexport) int sum(int a, int b)  
    {  
        return a + b;  
    }  
} </span>

Step 4:编译

直接编译即可。


二、在C#中通过P/Invoke调用Test.dll中的sum()方法

P/Invoke很简单。请看下面这段简单的C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace CSharpusedll
{
    class Program
    {
        [DllImport("Test.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern int sum(int a, int b);
        //加属性CallingConvention = CallingConvention.Cdecl,否则发生错误“托管的PInvoke签名与非托管的目标签名不匹配”
        static void Main(string[] args)
        {
            int result = sum(2, 3);
            Console.WriteLine("DLL func execute result: {0}", result);
            Console.ReadLine();
        }
    }
}

编译并执行这段C#程序,执行时别忘了把Test.dll拷贝到执行目录(Debug)中。

也可加EntryPoint属性,这样提供一个入口,以便C#里面可以用不同于dll中的函数名Sum。。

<span style="font-size:14px;">   [DllImport("Test.dll", EntryPoint = "sum")]
        private static extern int Sum(int a, int b);</span>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章