您的位置:首页 > 编程语言 > C语言/C++

关于c++和C#如何调用自己用c++写的dll文件

2012-12-17 18:35 411 查看
今天学习了,如何在c++和c#中通过调用自己写的dll文件中的函数来实现一定的功能。可能有些简单,但是有助于初学者学习。



首先分开讲解:

用c++编写dll文件(就是编写c++控制台程序):

// DLL.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"

extern "C" _declspec(dllexport) int add(int a,int b)
{
	return a+b;
}
_declspec(dllexport) int sub(int a,int b)
{
	return a-b;
}

这里可以看到两个的不同之处,add函数可以被c#调用,可是 sub函数值可以被c++程序调用。



其次编写测试c++调用上面的这个dll文件中的函数:

// DllTest.cpp : 定义控制台应用程序的入口点。  
//  
  
#include "stdafx.h"  
#include<iostream>  
  
  
using namespace std;  
 
//extern int add(int a,int b);
extern int sub(int a,int b);
  
int _tmain(int argc, _TCHAR* argv[])  
{  
   /* int i;  
    i=add(1,2);  
    cout<<"测试i="<<i<<endl; */

	int k;
	k= sub(8,6);
	cout<<"测试k="<<k<<endl; 

    int l;  
    cin >> l;  
    return 0;  
}

这里需要注意,要把生成的那个.dll和.lib文件一起 放在这个测试程序的.exe同一个文件夹中,同时还要通过添加现有项把这两个文件加载到这个工程中通常是资源文件中。



最后编写测试C#调用上面的这个dll中的函数:

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

namespace MyDllTestFile2
{ 
    class Program
    {
        [DllImport("MyDllFile.dll"/*, CallingConvention = CallingConvention.Cdecl*/)]

        public static extern int add(int a, int b);

        static void Main(string[] args)
        {
            Console.WriteLine("测试调用dll中的函数add" + add(2, 5));
            Console.Read();
        }
    }
}

这里需要注意的是,第一,默认入口点约定,第二,运行的时候需要把那个dll和这个应用程序exe在同一个文件夹中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: