教你快速在c#中调用C++代码(函数)

之前写过一段C++的代码,想给他用C#写个界面,也就是想让这段代码在C#中可以运行。看了百度的很多方法,都说是封装成dll调用,但是按照步骤来总会出现各种错误,像以下的这种:

并且迟迟不能解决,今天竟然有人跟我说直接把dll提取到C#工程的bin文件下就可以了,三观都毁了....尝试了一下,真的成功了,在这里把具体步骤和大家说一下,避免

在这种问题上浪费大量的时间。

首先,我们随便建立一个C++的工程(为了获取dll),将你打算在C#使用的函数用下面这种格式 extern "C" __declspec(dllexport) 封装一下:

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
using namespace std;

void output()
{
	cout << "hello world" << endl;
}
extern "C" __declspec(dllexport) int sum(int a, int b)
{
	output();
	return a + b;

}
然后右键点击工程名-->属性-->配置属性-->常规--->将配置类型改为dll

然后编译,将与工程名同级的debug文件夹下的dll提取,放置C#工程bin文件-->debug下,运行即可。

加上包  和begin,end之间的代码,然后在主程序中直接调用函数即可。

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

using System.Runtime.InteropServices;// 要加上

namespace Csharp
{
    class Program
    {
         //  begin
          [DllImport("Tach.dll",
          EntryPoint = "sum",
          CharSet = CharSet.Ansi,
          CallingConvention = CallingConvention.StdCall)]
          public static extern int sum(int a,int b);
          //end  
    
          static void Main(string[] args)
          {
              int res = sum(1, 2);
              Console.WriteLine(res);
          }
    }
}

结果如图,成功运行!


由于没有进行大量的测试,本方法可能存在问题(感觉和网上的都不一样.....),如果本方法有错误或者大家有更加好的方法,请在博客下留言,希望可以帮助到大家!


注:WPF中会发生错误!


  • 9
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
C# 调用 C++ DLL 函数的时候,如果函数的参数是 std::string 型,需要进行一些特殊的处理。因为在 C++ ,std::string 型实际上是一个,而在 C# 没有对应的型。 一种解决方案是,将 C++ 函数参数的 std::string 型改为 char* 型,并且增加参数来指定字符串的长度。在 C# ,可以使用 Marshal 的各种方法来将字符串转换为 char* 型,并将字符串的长度传递给 C++ 函数。 下面是一个示例代码,演示了如何在 C# 调用一个 C++ DLL 函数,该函数的参数型为 std::string: C++ DLL 函数代码: ```c++ #include <string> #include <iostream> // 定义一个使用 std::string 作为参数的函数 void printString(std::string str) { std::cout << str << std::endl; } ``` 在 C# 调用函数代码: ```c# using System; using System.Runtime.InteropServices; class Program { // 声明 C++ DLL 函数 [DllImport("MyCppLib.dll", CallingConvention = CallingConvention.Cdecl)] static extern void printString([MarshalAs(UnmanagedType.LPStr)] string str, int length); static void Main(string[] args) { // 要传递给 C++ DLL 函数的字符串 string myString = "Hello, world!"; // 将字符串转换为 char* 型,并获取字符串的长度 byte[] strBytes = System.Text.Encoding.ASCII.GetBytes(myString); int strLength = strBytes.Length; // 调用 C++ DLL 函数 printString(myString, strLength); } } ``` 在 C# ,使用 [MarshalAs(UnmanagedType.LPStr)] 特性将 C++ 函数参数的 std::string 型转换为 char* 型,使用 System.Text.Encoding.ASCII.GetBytes() 方法将字符串转换为 byte[] 型,并使用该数组的长度作为字符串的长度参数传递给 C++ 函数。 希望这个示例代码对您有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值