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

本文介绍了如何使用C#语言通过P/Invoke调用C++动态链接库中的函数,包括创建DLL的过程和在C#中进行调用的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

  Step 1:创建Win32 Console Application。本例中我们创建一个叫做“Test”的Solution。



  Step 2:将Application Type设定为DLL。在接下来的 Win32 Application Wizard 的 Application Settings 中,将 Application type 从 Console application 改为 DLL:



  Step 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#代码:

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

编译并执行这段C#程序,执行时别忘了把Test.dll拷贝到执行目录(Debug)中。

也可加EntryPoint属性,这样提供一个入口,以便C#里面可以用不同于dll中的函数名Sum。。

[DllImport("Test.dll", EntryPoint = "sum")]
private static extern int Sum(int a, int b);

参考:[科普小短文]在C#中调用C语言函数(静态调用Native DLL,Windows & Microsoft.Net平台)


 

转载于:https://www.cnblogs.com/peterYong/p/6556548.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值