并且迟迟不能解决,今天竟然有人跟我说直接把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);
          }
    }
}
由于没有进行大量的测试,本方法可能存在问题(感觉和网上的都不一样.....),如果本方法有错误或者大家有更加好的方法,请在博客下留言,希望可以帮助到大家!
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/nk_test/article/details/49785439