C#调用C++的方法

C#调用C++的方法



前言

供应商提供的SDK可能就是C++的库,因为效率问题需要在C++中处理数据(C++运行效率更高),在实际的工作中,总有这样的场景出现,那么如何在C#中调用C++的接口呢?


一、新建项目

我们新建两个项目,一个C++的动态连接可能(DLL),一个C#的WPF应用项目

二、步骤

编写一个函数
头文件

#pragma once
//测试是否成功
short TestFunc(short inputNum);

源文件

#include "pch.h"
#include "IExportFunc.h"
short TestFunc(short inputNum)
{
    
    
	if (inputNum <= 0)
	{
    
    
		return -1;
	}
	else
	{
    
    
		return inputNum + 1;
	}
}

添加-新建项:模块定义文件(.def)
在这里插入图片描述在模块定义文件Source.def中导出接口

LIBRARY

EXPORTS
TestFunc

在C#中调用C++接口

class Module
{
    
    
    [DllImport("CppProject.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern short TestFunc(short inputNum);
}
public partial class MainWindow : Window
{
    
    
    public MainWindow()
    {
    
    
        InitializeComponent();

        int i1 = Module.TestFunc(-2);

        int i2 = Module.TestFunc(3);
    }
}

三、运行结果

在这里插入图片描述

总结

不积硅步,何以至千里

猜你喜欢

转载自blog.csdn.net/Aflashstar/article/details/129708696
今日推荐