简介:文章包含在C#的环境下调用C++生成的DLL文件示例,和一些参考链接,参考链接才是核心,主要是微软的官方文档。
外部参考:
1. 新建工程
try_dll项目生成dll文件
calDll项目调用dll文件
image.png
2. DLL文件生成
proc.cpp
#include<iostream>
extern "C" _declspec(dllexport) int Add(int a, int b);
extern "C" _declspec(dllexport) int Minus(int, int);
extern "C" _declspec(dllexport) int Multi(int, int);
extern "C" _declspec(dllexport) void getArray(int *);
int Add(int a, int b)
{
return a + b;
}
int Minus(int a, int b)
{
return a - b;
}
int Multi(int a, int b)
{
return a * b;
}
void getArray(int * a)
{
printf("in C++:a[0]=%d,a[1]=%d,a[2]=%d\n",a[0],a[1],a[2]);
a[0] = 5;
a[1] = 12;
a[2] = 3;
a[3] = 91;
a[4] = 9;
}
属性页设置:配置类型--->动态库(.DLL)
输出目录:更改到你主程序输出的地方,这里是为了减少复制.DLL和.lib文件而做的,直接复制他们到主程序本来也是可以的,但是当你修改DLL项目后就得重新复制一遍,麻烦而且版本不好区分。
image.png
3.调用DLL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace calDll
{
class Program
{
[DllImport("try_dll.dll", CallingConvention = CallingConvention.Cdecl)]
extern static int Add(int a, int b);
[DllImport("try_dll.dll", CallingConvention = CallingConvention.Cdecl)]
extern static int Minus(int a, int b);
[DllImport("try_dll.dll", CallingConvention = CallingConvention.Cdecl)]
extern static int Multi(int a, int b);
[DllImport("try_dll.dll", CallingConvention = CallingConvention.Cdecl)]
extern static int getArray( int [] b);
static void Main(string[] args)
{
Console.WriteLine("in C#");
Console.WriteLine(Add(1, 2));
Console.WriteLine(Minus(1, 2));
Console.WriteLine(Multi(1, 2));
Console.WriteLine("C# send array to dll, then call it back");
int[] a = new int[] {8,8,8,8,8 };
getArray(a);
Console.WriteLine("in C#");
Console.WriteLine("a[0]={0}, a[1]={1},a[2]={2}",a[0],a[1],a[2]);
Console.ReadKey();
}
}
}
输出路径:
image.png
4.运行
-输出项
image.png
-
控制台结果
image.png
网友评论