如何在c++中创建在c#中使用的dll
本文关键字:dll 创建 c++ | 更新日期: 2023-09-27 18:16:37
我有个小问题想问你。
我有一个c++源代码和一个头文件。c++文件使用windows.h库,通过串口进行操作(基本操作:read(), write()等)。
我想做的是,使用这些文件创建一个库,并在我的 c#中使用该库。网络解决方案 .
我需要创建什么类型的库?我该怎么做呢?创建库后,如何将其导入c#解决方案?
致以最诚挚的问候。
我使用的代码部分:
// MathFuncsDll.h
namespace MathFuncs
{
class MyMathFuncs
{
public:
// Returns a + b
static __declspec(dllexport) double Add(double a, double b);
// Returns a - b
static __declspec(dllexport) double Subtract(double a, double b);
// Returns a * b
static __declspec(dllexport) double Multiply(double a, double b);
// Returns a / b
// Throws DivideByZeroException if b is 0
static __declspec(dllexport) double Divide(double a, double b);
};
}
// MathFuncsDll.cpp
// compile with: /EHsc /LD
#include "MathFuncsDll.h"
#include <stdexcept>
using namespace std;
namespace MathFuncs
{
double MyMathFuncs::Add(double a, double b)
{
return a + b;
}
double MyMathFuncs::Subtract(double a, double b)
{
return a - b;
}
double MyMathFuncs::Multiply(double a, double b)
{
return a * b;
}
double MyMathFuncs::Divide(double a, double b)
{
if (b == 0)
{
throw new invalid_argument("b cannot be zero!");
}
return a / b;
}
}
c# import part:
[DllImport("SimpleDll.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern double Add(double a, double b);
static void Main(string[] args)
{
string a = Add(1.0, 3.0));
}
经过一些注释,这里有一个尝试:
c++代码(DLL),例如。math.cpp编译成HighSpeedMath.dll:
extern "C"
{
__declspec(dllexport) int __stdcall math_add(int a, int b)
{
return a + b;
}
}
c#代码。Program.cs:
namespace HighSpeedMathTest
{
using System.Runtime.InteropServices;
class Program
{
[DllImport("HighSpeedMath.dll", EntryPoint="math_add", CallingConvention=CallingConvention.StdCall)]
static extern int Add(int a, int b);
static void Main(string[] args)
{
int result = Add(27, 28);
}
}
}
当然,如果入口点已经匹配,则不必指定它。调用约定相同。
正如在注释中提到的,DLL必须提供一个c接口。这意味着,extern "C",没有异常,没有引用等。
编辑:如果你有一个DLL的头文件和一个源文件,它可能看起来像这样:
math.hpp
#ifndef MATH_HPP
#define MATH_HPP
extern "C"
{
__declspec(dllexport) int __stdcall math_add(int a, int b);
}
#endif
math.cpp
#include "math.hpp"
int __stdcall math_add(int a, int b)
{
return a + b;
}
您需要将c++代码编译成动态链接库,并在c#中执行以下操作:
class MyClass
{
[DllImport("MyDLL.dll")]
public static extern void MyFunctionFromDll();
static void Main()
{
MyFunctionFromDll();
}
}
您可以使用c# DllImport和dllport作为DLL互操作演练的起点。这里是平台调用教程
除了Lichian提供的编译成一个普通的DLL和使用p/invoke,这可能是最简单的方法你也可以将c++创建为COM组件(可能你不想这样做),第三种选择是添加一个c++/CLI的薄层例如
using namespace System;
namespace youcomany{ namespace CPPWrapper
{
Wrapper::Function(String^ parameter)
{
//call the rest of you C++ from here
}
}}