C# 调用 Linux 共享库 (SO) 函数 - mytest.so 示例
C# 调用 Linux 共享库 (SO) 函数 - mytest.so 示例
本教程将演示如何在 C# 项目中调用 Linux 共享库 (SO) 文件中的函数。我们将以 mytest.so 中的 sum 函数为例,并给出使用 mono 编译运行的完整步骤。
步骤:
-
创建 C# 项目: 创建一个新的 C# 项目,例如命名为 MyTest。
-
放置共享库文件: 将 mytest.so 文件放到 MyTest 项目的根目录下。
-
调用函数: 在 MyTest 项目的代码中使用
DllImport属性调用 sum 函数,示例代码如下:
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport('mytest.so')]
public static extern int sum(int a, int b);
static void Main(string[] args)
{
int result = sum(1, 2);
Console.WriteLine('The result is: ' + result);
}
}
- 编译运行: 打开终端,使用 mono 编译并运行该程序,例如:
$ mono MyTest.exe
- 输出结果: 程序会输出以下内容,表明成功调用了 mytest.so 中的 sum 函数:
The result is: 3
注意:
- mytest.so 文件需要事先编译生成,并确保其包含 sum 函数。
- 确保您的系统已安装 mono,并配置好环境变量。
- 可以根据实际情况修改代码和命令。
原文地址: https://www.cveoy.top/t/topic/nyxr 著作权归作者所有。请勿转载和采集!