首页 技术 正文
技术 2022年11月18日
0 收藏 717 点赞 3,277 浏览 1224 个字

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

源码:百度网盘

环境:win7+vs2010。

1、打开VS创建C++项目”C++_CScharp_DLL”

C++和C#混合编程

点击确定之后接着点击下一步:

C++和C#混合编程

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

C++和C#混合编程

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

2、添加代码文件

右键项目,添加类,如下图所示:

C++和C#混合编程

添加类之后会打开添加文件对话框,点击添加即可,如下图所示:

C++和C#混合编程

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

C++和C#混合编程

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

C++和C#混合编程

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++和C#混合编程

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

打开项目属性

C++和C#混合编程

C++和C#混合编程

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

C++和C#混合编程

3、添加测试程序:

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

C++和C#混合编程

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

C++和C#混合编程

添加完后设为启动项:

C++和C#混合编程

添加引用:

C++和C#混合编程

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

C++和C#混合编程

4、编写测试代码

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(, ));
Console.WriteLine(fun.say("Hello World"));
Console.ReadKey();
}
}
}

现在就可以点击调试按钮调试了,调试结果如图所示:

C++和C#混合编程

异常情况:

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

C++和C#混合编程

修改方法如下:

C++和C#混合编程

源码:百度网盘

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,557
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898