分享

c 制作dll文件

 SamBookshelf 2013-08-08
c 制作dll文件

dll文件的c 制作
1、首先用vs2005建立一个c 的dll动态链接库文件,这时,
// DllTest.cpp : 定义 DLL 应用程序的入口点。
//

#include "stdafx.h"
//#include "DllTest.h"

#ifdef _MANAGED
#pragma managed(push, off)
#endif

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD ul_reason_for_call,
                       LPVOID lpReserved
           )
{
    return TRUE;
}

#ifdef _MANAGED
#pragma managed(pop)
#endif
这段代码会自动生成,
2、自己建一个DllTest.h的头文件,和DllTest.def的块声明文件。
其中头文件是为了声明内部函数使用。块声明主要是为了在dll编译成功后固定好方法名。别忘记添加#include "DllTest.h"
3、在DllTest.h中加入如下代码
#ifndef DllTest_01
#define DllTest_01
#define EXPORT extern "C" __declspec(dllexport)
//两个参数做加法
EXPORT int _stdcall Add(int iNum1=0,int iNum2=0);
//两个参数做减法
EXPORT int _stdcall Subtraction(int iNum1=0,int iNum2=0,int iMethod=0);
#endif
4、在DllTest.def中加入如下代码
LIBRARY    "DllTest"
EXPORTS
Add
Subtraction
5、在DllTest.cpp中写好代码为
// DllTest.cpp : 定义 DLL 应用程序的入口点。
//

#include "stdafx.h"
#include "DllTest.h"

#ifdef _MANAGED
#pragma managed(push, off)
#endif

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD ul_reason_for_call,
                       LPVOID lpReserved
           )
{
    return TRUE;
}

#ifdef _MANAGED
#pragma managed(pop)
#endif

//加函数
int APIENTRY Add(int a,int b)   // APIENTRY 此关键字不可少
{
return (a b);
}
//减函数
int APIENTRY Subtraction(int a,int b,int i)
{
if(0==i)
    return (a-b);
else
    return (b-a);
}
6、这样编译生成就可以得到对应的DllTest.dll的文件了
二、C#调用dll文件
1、创建一个c#的控制台程序(当然其他也没有问题),自动生成以下代码
using System;
using System.Collections.Generic;
using System.Text;
//using System.Runtime.InteropServices;

namespace CSharpIncludeC__Dll
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}
2、添加命名空间using System.Runtime.InteropServices;
3、若要引用dll文件,首先吧dll文件自行拷贝到bin\debug,文件夹下,没有的话,先编译一下。
4、添加属性
[DllImport("DllTest.dll", CharSet = CharSet.Ansi)]
static extern int Add(int iNum1, int iNum2);
5、最终产生代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace CSharpIncludeC__Dll
{
    class Program
    {
        [DllImport("DllTest.dll", CharSet = CharSet.Ansi)]
        static extern int Add(int iNum1, int iNum2);

        [DllImport("DllTest.dll", CharSet = CharSet.Ansi)]
        static extern int Subtraction(int iNum1,int iNum2,int iMethod);

        static void Main(string[] args)
        {
            int iValue = Add(1, 2);
            Console.WriteLine(iValue);
            iValue = Subtraction(1, 2, 1);
            Console.WriteLine(iValue);
            Console.Read();
        }
    }
}
6、生成项目运行就可以了,结果是3和1


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多