c|c++ 封装 c# 调用的动态库
需要注意的地方:
1、定义接口函数方式:
extern "C" void __stdcall Function();
2、工程中加入模块定义def文件:
一定要通过vs向导加,自己手动加的,后面不知道怎么回事就丢失配置了,自己这次弄花了比较多时间应该就是这个坑
然后在属性页-》配置属性-》链接器中添加def文件
3、如果用到静态库,opencv 需要手动下载,之前用nuget自动配置,没找到静态库
4、其他注意配置项
5、目标平台的对应
生成的dll文件,本地C#调用没问题,但给别人使用时却出现找不到dll的问题,这个可以的原因有:
1)在程序搜索的文件路径下没有该dll
2)目标平台不对应,库是x86的,而c#是x64的
3)生成的dll可能依赖其他的dll文件,需要将依赖的dll文件也异同放到c#的工程可访问的路径下
案例:
---autofocus.h---
#ifndef _CALSOBEL_H_
#define _CALSOBEL_H_
extern "C" void __stdcall InitMem(short _height, short _width, int _channel = 1)
#endif
---autofocus.def---
LIBRARY
EXPORTS InitMem
---autofocus.cpp---
#include "autofocus.h"
// 计算sobel
extern "C" double __stdcall InitMem()
{
....
}
最后生成的文件:
5 c# 调用:
lib、dll文件放到bin\debug目录下
using System;
using System.Runtime.InteropServices;
namespace test_csharp
{
class Program
{
[DllImport(@"autofocus.dll", EntryPoint = "CalSobelVal", CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.StdCall)]
public static extern double CalSobelVal(string imgFilePath);
static void Main(string[] args)
{
double sobel = CalSobelVal("D:/building.jpg");
Console.WriteLine(sobel);
Console.ReadLine();
}
}
}