温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#调用c++的标准动态链接库dll

发布时间:2020-05-31 16:54:41 来源:网络 阅读:306 作者:huangchaosuper 栏目:编程语言

  一、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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI