公共语言运行库 (CLR) 的 interop 功能(称为平台调用 (P/Invoke)),可以使用 P/Invoke 来调用 Windows API 函数。P/Invoke简介

官网:Marshaling Data with Platform Invoke  包含平台调用类型转换

动态链接库,windows环境的格式是.dll,linux环境的是.so。 不能引用静态库.lib 或 .a

引用的时候,[DllImport("Test.dll", EntryPoint = "sum")]

可以简写为Test,
[DllImport("Test", EntryPoint = "sum")]
windows环境下自动取寻找Test.dll,Linux环境下自动寻找 libTest.so

一、VS 用 C++ 创建动态链接库

C# 通过P/Invoke调用C/C++函数

  1. 创建Win32 Console Application。本例中我们创建一个叫做“Test”的Solution。
  2. 将Application Type设定为DLL。在接下来的 Win32 Application Wizard 的 Application Settings 中,将 Application type 从 Console application 改为 DLL:
  3. 将方法暴露给DLL接口。现在在这个Solution中,目录和文件结构是这样的:

编辑 Test.cpp 如下:

#include "stdafx.h"    
extern "C"  
{  
    _declspec(dllexport) int sum(int a, int b)  
    {  
        return a + b;  
    }  
} 

Step 4:编译

直接编译即可。

二、在C#中通过P/Invoke调用Test.dll中的sum()方法

P/Invoke很简单。请看下面这段简单的C#代码:

C# 通过P/Invoke调用C/C++函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace CSharpusedll
{
    class Program
    {
        [DllImport("Test.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern int sum(int a, int b);
        //加属性CallingConvention = CallingConvention.Cdecl,否则发生错误“托管的PInvoke签名与非托管的目标签名不匹配”
        static void Main(string[] args)
        {
            int result = sum(2, 3);
            Console.WriteLine("DLL func execute result: {0}", result);
            Console.ReadLine();
        }
    }
}
View Code

相关文章:

  • 2021-07-31
  • 2022-12-23
  • 2021-09-21
  • 2021-12-06
  • 2021-09-16
  • 2022-12-23
  • 2021-10-18
猜你喜欢
  • 2021-06-06
  • 2021-11-03
  • 2021-08-22
相关资源
相似解决方案