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();
        }
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章