Skip to content

NET调用C++

约 195 字小于 1 分钟

NET

2026-01-13

方式

  • 传统方式中一般使用 DllImport,P/Invoke
  • NativeLibrary 5/6/7/8+支持 用于灵活可控的加载使用本机动态链接库(.dll.so、- .dylib)。属于 System.Runtime.InteropServices名称空间

NativeLibrary

using System;
using System.Runtime.InteropServices;

/******1.加载本地库*********/
// 示例:加载当前目录下的 mylib.dll (Windows) 或 libmylib.so (Linux)
IntPtr handle = NativeLibrary.Load("mylib"); // 会自动加平台后缀
// 或指定完整路径:
// IntPtr handle = NativeLibrary.Load("./lib/mylib.so");
/*
> `NativeLibrary.Load` 会按平台自动尝试:
> Windows: `mylib.dll`
> Linux: `libmylib.so`
> macOS: `libmylib.dylib`
*/




/******2.获取函数地址***********/
bool success = NativeLibrary.TryGetExport(handle, "Add", out IntPtr addPtr);
if (!success) throw new InvalidOperationException("Function 'Add' not found.");



/*******3.将函数指针转换为委托delegate*****************/
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate int AddDelegate(int a, int b);

var addFunc = Marshal.GetDelegateForFunctionPointer<AddDelegate>(addPtr);
int result = addFunc(3, 4); // 调用