c# 调用静态库
时间: 2023-06-30 16:17:44 浏览: 146
在 C# 中调用静态库需要使用 P/Invoke(平台调用)机制。以下是一个简单的示例代码,演示了如何在 C# 中调用 C++ 编写的静态库中的函数:
```csharp
using System;
using System.Runtime.InteropServices;
class Program
{
// 声明需要调用的函数
[DllImport("mylib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int my_function(int arg1, int arg2);
static void Main()
{
// 调用函数
int result = my_function(1, 2);
Console.WriteLine(result);
}
}
```
其中 `mylib.dll` 是静态库编译后生成的动态链接库文件,`my_function` 是静态库中的函数名。在声明函数时需要指定 `CallingConvention = CallingConvention.Cdecl`,表示采用 C 语言调用约定。
需要注意的是,静态库中的函数必须使用 C 语言编写,并且需要使用 `extern "C"` 包裹函数声明,以避免 C++ 编译器对函数名进行命名修饰。例如:
```cpp
extern "C" int my_function(int arg1, int arg2)
{
// ...
}
```