C# 调用VC++的DLL,VC++封装DLL

VS中新建一个动态库项目

文件生成一个工程名对应的.cpp文件,该文件定义 DLL应用程序的导出函数。

工程内新建一个类OutputInt,我用类向导生成,工程中会添加OutputInt.cpp和OutputInt.h两个文件,

在.h文件中声明函数

#pragma once
class OutputInt
{
public:
    OutputInt();
    ~OutputInt();
    
    static _declspec(dllexport)  int TestFunction();
};

在.cpp文件中实现 构造函数、析构函数和 自定义函数

#include "stdafx.h"
#include "OutputInt.h"


OutputInt::OutputInt()
{
}


OutputInt::~OutputInt()
{
}


int OutputInt::TestFunction()
{
    return 111;
}

类和头文件都实现了。

然后在Win32Project1.cpp中定义对外暴露的函数

#include "stdafx.h"
#include "OutputInt.h"

extern "C" __declspec(dllexport) int TestFunction()
{
    OutputInt outPut;
    return outPut.TestFunction();
}

编译,生成对应工程项目名的DLL文件,动态链接库生成完成。

在C# WPF应用程序中调用以上生成的DLL

把生成的DLL文件拷贝到 WPF工程的DEBUG文件夹下,调用方式:

[DllImport("Win32Project1.dll", ExactSpelling = false)]
 public static extern int TestFunction();

调用完成。

原文地址:https://www.cnblogs.com/pangkang/p/5856144.html