在C#中调用C++编写的动态库(DLL)通常使用平台调用服务(Platform Invocation Services,简称P/Invoke)或C++/CLI包装器。以下是两种常见的技术实现方案及演示代码。
方案一:使用P/Invoke直接调用C++ DLL
P/Invoke允许C#代码直接调用C++编写的非托管DLL中的函数。以下是一个简单的示例:
1. C++ DLL代码
假设我们有一个简单的C++ DLL,代码如下:
cpp
复制
// MyLibrary.h
#ifdef MYLIBRARY_EXPORTS
#define MYLIBRARY_API __declspec(dllexport)
#else
#define MYLIBRARY_API __declspec(dllimport)
#endif
extern "C" MYLIBRARY_API int Add(int a, int b);
// MyLibrary.cpp
#include "MyLibrary.h"
MYLIBRARY_API int Add(int a, int b) {
return a + b;
}
编译生成 MyLibrary.dll。
2. C# 调用代码
在C#中使用P/Invoke调用这个DLL:
csharp
复制
using System;
using System.Runtime.InteropServices;
class Program
{
// 声明DLL中的函数
[DllImport("MyLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int Add(int a, int b);
static void Main(string[] args)
{
int result = Add(3, 4);
Console.WriteLine("The result is: " + result);
}
}
方案二:使用C++/CLI包装器
C++/CLI可以在C++和C#之间提供一个桥梁,使得C#可以更方便地调用C++代码。
1. C++/CLI 包装器代码
创建一个C++/CLI项目,编写包装器代码:
cpp
复制
// MyWrapper.h
#pragma once
using namespace System;
namespace MyWrapper {
public ref class MyMath {
public:
static int Add(int a, int b);
};
}
// MyWrapper.cpp
#include "MyWrapper.h"
#include "MyLibrary.h"
namespace MyWrapper {
int MyMath::Add(int a, int b) {
return ::Add(a, b);
}
}
编译生成 MyWrapper.dll。
2. C# 调用代码
在C#中引用 MyWrapper.dll 并调用包装器:
csharp
复制
using System;
using MyWrapper;
class Program
{
static void Main(string[] args)
{
int result = MyMath.Add(3, 4);
Console.WriteLine("The result is: " + result);
}
}
总结
-
P/Invoke 适用于简单的函数调用,且不需要复杂的对象传递。
-
C++/CLI 适用于需要更复杂的交互,或者在C++和C#之间传递对象的情况。
如果对这个话题感兴趣欢迎留言,我将继续展开深入探讨。谢谢



1887

被折叠的 条评论
为什么被折叠?



