切换主题
使用C++调用C#开发的DLL
本文档介绍如何在C++项目中调用由C#开发的DLL文件。
前置条件
- 确保已安装以下工具:
- Visual Studio(支持C++和C#开发)
- .NET Framework(与C# DLL兼容的版本)
- 已有一个由C#开发的DLL文件。
C# DLL开发注意事项
- 在C#项目中,确保导出的类和方法使用
public
修饰符。 - 使用
[DllExport]
或[ComVisible(true)]
属性导出方法。 - 如果使用COM互操作,需注册DLL:bash
regasm YourLibrary.dll /codebase
1
在C++中调用C# DLL的步骤
1. 引入必要的头文件
在C++项目中,使用以下头文件:
cpp
#include <windows.h>
1
2. 加载DLL
使用LoadLibrary
函数加载DLL:
cpp
HINSTANCE hDll = LoadLibrary(L"YourLibrary.dll");
if (!hDll) {
// 错误处理
return -1;
}
1
2
3
4
5
2
3
4
5
3. 获取函数指针
使用GetProcAddress
获取导出函数的地址:
cpp
typedef int (*YourFunctionType)(int, int);
YourFunctionType YourFunction = (YourFunctionType)GetProcAddress(hDll, "YourFunctionName");
if (!YourFunction) {
// 错误处理
FreeLibrary(hDll);
return -1;
}
1
2
3
4
5
6
7
2
3
4
5
6
7
4. 调用函数
调用获取的函数指针:
cpp
int result = YourFunction(10, 20);
1
5. 释放DLL
使用FreeLibrary
释放DLL:
cpp
FreeLibrary(hDll);
1
示例代码
以下是完整的示例代码:
cpp
#include <windows.h>
#include <iostream>
typedef int (*AddFunction)(int, int);
int main() {
HINSTANCE hDll = LoadLibrary(L"YourLibrary.dll");
if (!hDll) {
std::cerr << "Failed to load DLL." << std::endl;
return -1;
}
AddFunction Add = (AddFunction)GetProcAddress(hDll, "Add");
if (!Add) {
std::cerr << "Failed to find function." << std::endl;
FreeLibrary(hDll);
return -1;
}
int result = Add(10, 20);
std::cout << "Result: " << result << std::endl;
FreeLibrary(hDll);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
注意事项
- 确保DLL文件与C++项目在同一目录,或将DLL路径添加到系统环境变量。
- 如果使用COM互操作,需正确注册DLL。
- 检查函数签名是否匹配,避免调用失败。