一、C++ 生成DLL
打开VS,新建C++动态链接库项目
新建一个头文件
在DllTest.h中写入内容
#include<string>
using namespace std;
extern “C” _declspec(dllexport) int __stdcall test01(int a, int b, int c);
extern “C” __declspec(dllexport) char* __stdcall test02(char* in_string);
在DllTest.cpp中写入内容
#include “stdafx.h”
#include “DllTest.h”
int __stdcall test01(int a, int b, int c)
{
return a + b + c;
}
char* __stdcall test02(char* in_string)
{
return in_string;
}
点击生成可生成DllTest.dll文件
二、新建C#项目,将DllTest.dll复制到项目下
Program.cs调用代码如下:
class Program
{
[DllImport(“DllTest.dll”,CharSet = CharSet.Ansi)]
extern static int test01(int a, int b, int c);
[DllImport(“DllTest.dll”, CharSet = CharSet.Ansi)]
public static extern IntPtr test02(IntPtr inString);
static void Main(string[] args)
{
Console.WriteLine(“test01结果:” + test01(2,3,5));
IntPtr input = Marshal.StringToHGlobalAnsi(“HelloWorld”);
Console.WriteLine(“test02结果:” + Marshal.PtrToStringAnsi(test02(input)));
Console.ReadKey();
}
}