ITPub博客

首页 > Linux操作系统 > Linux操作系统 > C#与C++的非托管代码交互小试

C#与C++的非托管代码交互小试

原创 Linux操作系统 作者:iDotNetSpace 时间:2009-12-10 15:57:38 0 删除 编辑

第一次用C#调用C/C++生成的DLL文件,感觉有点新奇,其实只是实现了运行在公共语言运行库 (CLR) 的控制之外的“非托管代码”(运行在公共语言运行库(CLR)的控制之中的代码码称为“托管代码“)的东西,怎样运用在托管下的非托管呢?现在给感兴趣的初学者简单地写一个实现的全过程吧(有什么问题千万别笑):

1.用VS2008选择其它语言(C++)创建一个控制台应用程序命名为Mydll1,然后选择应用程序类型为DLL,确定

 项目如图:

 

在头文件 stdafx.h 下添加如下声明:

 

<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->#define LIBEXPORT_API extern "C" __declspec(dllexport) 
LIBEXPORT_API 
int Add(int a, int b);

 

 

在MyDll.cpp中实现这个函数:

<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->

#include 
"stdafx.h"

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

 

注意如果实现的方法是声明在其它头文件中的,一定要 加#include "xxx.h" 来引用这个声明了这个函数头文件。

生成MyDll.dll和MyDll.lib。

2.在Visual C# .net中引用dll文件

新建Visual C#控制台应用程序命名为TestImportDll;

将MyDll.dll和MyDll.lib拷贝到可执行文件目录下(如图):

在Praogram.cs中添加引用using System.Runtime.InteropServices;

按如下方式声明一个将要引用MyDll.dll中函数的类:

  

<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> class test
    {
        
//[DllImport("..\\..\\lib\\CppDemo.dll")]
        
//public static extern void Function();

        
//[DllImport("..\\..\\lib\\CppDemo.dll")]
        
//public static extern int Add(int i, int j);
        [DllImport("..\\..\\Lib\\Mydll1.dll")]
        
public static extern int Add(int a, int b);
    }

 

 最后在Main函数中调用这个类输出结果:

 

<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> static void Main(string[] args)
        {           

            Console.WriteLine(
"result: " + test.Add(2, 3).ToString());

            Console.ReadLine();
        }
下面是Program.cs的代码:
END(如图):

 

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-622136/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-01-04

  • 博文量
    2376
  • 访问量
    5769027