前言
在C++中,通过DLL导出函数,通常使用__declspec(dllexport)修饰符。在C#中,通过DllImport来导入C++ DLL中的函数。确保参数类型在C++和C#之间正确对齐非常重要,在 C++ 开发 DLL 提供给 C# 使用的过程中,导出函数的参数类型可以包括多种。以下是一些常见的参数类型,以及每种类型的示例,同时提供了相应的 C# DllImport
函数的编写方式。
基础类型对照
C++ 数据类型 | C# 数据类型 |
---|---|
int | int |
unsigned int | uint |
short | short |
unsigned short | ushort |
long | long |
unsigned long | ulong |
float | float |
double | double |
char | char |
unsigned char | byte |
wchar_t | char (UTF-16) |
bool | bool |
void | void |
int* | IntPtr |
unsigned int* | IntPtr |
double* | IntPtr |
char* | string (or IntPtr for raw memory) |
const char* | string (or IntPtr for raw memory) |
struct | struct (with [StructLayout] if needed) |
HANDLE | IntPtr |
处理案例
1. 处理基础类型:
C++ 导出函数:
// YourLibrary.h
#ifndef YOURLIBRARY_H
#define YOURLIBRARY_H
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) int AddTwoNumbers(int a, int b);
#ifdef __cplusplus
}
#endif
#endif // YOURLIBRARY_H
C# 导入函数:
// YourCSharpCode.cs
class Program {
[DllImport("YourLibrary.dll")]
public static extern int AddTwoNumbers(int a, int b);
static void Main() {
int result = AddTwoNumbers(3, 4);
Console.WriteLine(result); // 输出 7
}
}
2. 处理指针类型:
C++ 导出函数:
// YourLibrary.h
#ifndef YOURLIBRARY_H
#define YOURLIBRARY_H
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) void MultiplyByTwo(int* value);
#ifdef __cplusplus
}
#endif
#endif // YOURLIBRARY_H
C# 导入函数:
// YourCSharpCode.cs
class Program {
[DllImport("YourLibrary.dll")]
public static extern void MultiplyByTwo(ref int value);
static void Main() {
int number = 5;
MultiplyByTwo(ref number);
Console.WriteLine(number); // 输出 10
}
}
3. 处理指针数组:
C++ 导出函数:
// YourLibrary.h
#ifndef YOURLIBRARY_H
#define YOURLIBRARY_H
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) void IncrementArray(int* array, int size);
#ifdef __cplusplus
}
#endif
#endif // YOURLIBRARY_H
C# 导入函数:
// YourCSharpCode.cs
class Program {
[DllImport("YourLibrary.dll")]
public static extern void IncrementArray(int[] array, int size);
static void Main() {
int[] numbers = {
1, 2, 3, 4, 5 };
IncrementArray(numbers, numbers.Length);
Console.WriteLine(string.Join(", ", numbers)); // 输出 2, 3, 4, 5, 6
}
}
4. 处理处理结构体:
C++ 导出函数:
// YourLibrary.h
#ifndef YOURLIBRARY_H
#define YOURLIBRARY_H
#ifdef __cplusplus
extern "C" {
#endif
struct Point {
int x;
int y;
};
__declspec(dllexport) int CalculateDistance(const Point* p1, const Point* p2);
#ifdef __cplusplus
}
#endif
#endif // YOURLIBRARY_H
C# 导入函数:
// YourCSharpCode.cs
[StructLayout(LayoutKind.Sequential)]
public struct Point {
public int x;
public int y;
}
class Program {
[DllImport("YourLibrary.dll")