C#调用C++代码

目录

1.本文目的

2.创建一个C++程序

3.创建一个C#程序

4.C#调用C++类内的函数


1.本文目的

在进行C++/C#开发时,有时会遇到“给C++项目加C#界面”、“用C++实现C#基础功能”等问题而无从下手。本文将介绍一个非常简单的例子:C#调用C++的一个加法函数,再调用类内的减法函数,以此来介绍如何C#通过dll调用C++代码

2.创建一个C++程序

1.新建一个C++ Win32控制台应用程序工程,命名为CppDLL,点击“确定”

2.弹出的框框中点“下一步”,然后选中“dll”,点击“完成”


3.程序自动创建了CppDLL.cpp,打开并输入以下内容:

#include "stdafx.h"
extern "C" __declspec(dllexport) int Add(int a, int b)
{
    return a + b;
}

4.按一下F5编译代码。自动在Debug目录下生成了dll和lib文件。等下C#程序就是通过这2个文件来调用Add()函数


3.创建一个C#程序

1.新建一个C# 控制台应用程序(Windows窗体应用程序一样简单,后面的步骤变通下即可),并命名为“InvokeCpp”

2.把刚才的dll和lib文件拷贝到这个C#工程的Debug目录下


3.新建一个类,并命名为“InvokeAdd”。这个类用来调用dll


4. InvokeAdd的代码如下。 主要是 添加了预处理命令using System.Runtime.InteropServices;和 函数内的两行代码

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace InvokeCpp
{
    class InvokeAdd
    {
        [DllImport("CppDLL.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
        public static extern int Add(int x, int y);
    }
}

5.打开Program.cs。在其main函数中调用此类,代码如下。运行结果1+2=3,成功在控制台显示。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace InvokeCpp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(InvokeAdd.Add(1, 2).ToString());
            Console.ReadLine();
        }
    }
}

4.C#调用C++类内的函数

到目前为止已经能调用C++一些基本函数,但是如果函数是封装在类当中呢?简单的方法调用其实一样简单,以下内容介绍如何通过对象调用类内的函数实现减法运算。

1.  打开刚才的C++项目,添加头文件MinusOperation.h


2.头文件输入内容:

class MinusOperation
{
public:
    int minus(int a, int b);
};

3新建MinusOperation.cpp并输入内容:

#include"stdafx.h"
#include"MinusOperation.h"
extern "C" __declspec(dllexport) int minus(int a, int b)
{
    return a - b;
}

4.按F5编译,并把dll和 lib复制到C#工程的Debug文件夹下

5. InvokeAdd.cs的代码修改如下:

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
 
namespace InvokeCpp
{
    class InvokeAdd
    {
        [DllImport("CppDLL.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
        public static extern int Add(int x, int y);
 
        [DllImport("CppDLL.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
        public static extern int minus(int x, int y);
    }
}

6. Program.cs的代码修改如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace InvokeCpp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(InvokeAdd.Add(1, 2).ToString());
            Console.WriteLine(InvokeAdd.minus(1, 2).ToString());
            Console.ReadLine();
        }
    }
}

7.运行结果1-2=-1,正确

发布了70 篇原创文章 · 获赞 17 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/hwj_wayne/article/details/104064171
今日推荐