c#调用c++类中的方法(onnx C++部署)

环境:vs2019 community

场景:探索c#调用C++类,用于部署深度学习onnx C++模型。

创建c++空项目Project3

在project3下新建AIDetector类

ai_detector.h

#pragma once

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

#ifdef CaculateDLL_EXPORTS
#define Calculate_EXPORTS __declspec(dllexport)
#else
#define Calculate_EXPORTS __declspec(dllimport)
#endif


class AIDetector
{
public:
    AIDetector();
    ~AIDetector();
    int Add(int numberA, int numberB);
};

ai_detector.cpp

#define CaculateDLL_EXPORTS
#include "ai_detector.h"
#include <iostream>

AIDetector::AIDetector()
{
    std::cout << "init caculator" << std::endl;
}


AIDetector::~AIDetector()
{
    std::cout << "release caculator" << std::endl;
}

int AIDetector::Add(int numberA, int numberB)
{
    return numberA + numberB;
}

接下来是将需要调用的方法Add()暴露出来,其实就是外包一次Add()方法。

dll_wrapper.h

#pragma once
// DLLTest.h
#pragma once
#include "ai_detector.h"
namespace DLLTestWrapper {
	extern "C" Calculate_EXPORTS int __stdcall add(int x, int y);
}

dll_wrapper.cpp

// DLLTest.cpp
#pragma once
#include "dll_wrapper.h"
namespace DLLTestWrapper {
	AIDetector* api = new AIDetector(); // 此处声明一个内部类的指针
	int add(int x, int y) {
		return api->Add(x, y); // 此处调用内部类的方法实现暴露类方法
	}
}

输出dll文件

改变项目属性,右击项目名称

 输出目录就是你想dll保存到哪个目录。

点击生成项目,然后就生成了三个文件Project.dll,Project.lib, Project.pdb

创建C#工程ConsoleApp1

Program.cs

using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            [DllImport(@"Project3.dll")]
            static extern int add(int a, int b);

            int x = add(2, 3);
            
            int x2 = add(3, 5);

            int x3 = add(4, 6);

        }
    }
}

 把Project3.dll文件拷贝到C#工程工作目录下,我的是***ConsoleApp1\bin\Debug\netcoreapp3.1

 运行效果:

注意到,虽然调用了三次add方法,但是只初始化了一次AIDetector类,这就是我们需要的效果。

猜你喜欢

转载自blog.csdn.net/jizhidexiaoming/article/details/121102675