C++和C#混合编程

最近须要利用C++和C#混合编程,而后就写了一个C#调用C++生成的DLL的DEMO。困扰我很久的就是C#中string类型在C++里面怎么表达,如今把C++生成DLL供C#调用的流程写出来。编程

源码:百度网盘测试

 

环境:win7+vs2010。spa

 

一、打开VS建立C++项目"C++_CScharp_DLL"3d

点击肯定以后接着点击下一步:调试

而后选择应用程序和附加选项:code

点击完成,C++的项目就新建好了。blog

二、添加代码文件get

右键项目,添加类,以下图所示:源码

添加类以后会打开添加文件对话框,点击添加便可,以下图所示:string

点击肯定以后进去下一个对话框,填写文件名Function,以下图所示:

添加好后会生成h文件和cpp文件,以下图所示:

Function.h文件代码以下:

#pragma once
#include <string>
public ref class Function
{
public:
    Function(void);
    ~Function(void);
    int menber;
    int menberFuncAdd(int a,int b);
    System::String^ say(System::String^ str);
};

Function.cpp文件代码以下:

#include "Function.h"


Function::Function(void)
{
}


Function::~Function(void)
{
}

int Function::menberFuncAdd(int a,int b)
{
   return a+b;
}
System::String^ Function::say(System::String^ str)
{
   return str;
}

填写完后Function.h文件会报错,错误类型以下:

这里须要在C++项目里面设置,让动态库受到公共语言运行时的支持。以下图所示:

打开项目属性

修改完成后点击项目右键生成DLL,看是否报错,成功结果以下图:

三、添加测试程序:

在该解决方案中添加测试程序:

添加一个C#控制台测试程序:

添加完后设为启动项:

添加引用:

将C++项目添加到C#的项目中:

四、编写测试代码

Program.cs文件代码以下:

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

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Function fun = new Function();
            Console.WriteLine(fun.menberFuncAdd(1, 2));
            Console.WriteLine(fun.say("Hello World"));
            Console.ReadKey();
        }
    }
}

如今就能够点击调试按钮调试了,调试结果如图所示:

 

异常状况:

运行的时候若出现未处理的异常致使dll加载失败,须要修改项目到对应的平台

 

修改方法以下:

 

源码:百度网盘

相关文章
相关标签/搜索