c# 调用c++ dll 简单实验

这篇博客展示了如何使用C#客户端调用C++编译的DLL进行函数操作。C++代码定义了一个导出函数`add`,C#通过`DllImport`调用来实现跨语言交互,完成简单的加法运算并打印结果。

1.概要

1.1 dll c++

// 当使用预编译的头时,需要使用此源文件,编译才能成功。
extern "C" __declspec(dllexport) INT32 add(INT32 a, INT32 b)
{
    return (a + b);
}

1.2 客户端  c#

[DllImport("Dll1.dll")]
        public static extern int add(int a, int b);
        static void Main(string[] args)
        {
            int a = add(1, 2);

 

2.代码

2.1 dll c++

// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "pch.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

 

// pch.h: 这是预编译标头文件。
// 下方列出的文件仅编译一次,提高了将来生成的生成性能。
// 这还将影响 IntelliSense 性能,包括代码完成和许多代码浏览功能。
// 但是,如果此处列出的文件中的任何一个在生成之间有更新,它们全部都将被重新编译。
// 请勿在此处添加要频繁更新的文件,这将使得性能优势无效。

#ifndef PCH_H
#define PCH_H

// 添加要在此处预编译的标头
#include "framework.h"

#endif //PCH_H

 

#pragma once

#define WIN32_LEAN_AND_MEAN             // 从 Windows 头文件中排除极少使用的内容
// Windows 头文件
#include <windows.h>
// pch.cpp: 与预编译标头对应的源文件

#include "pch.h"

// 当使用预编译的头时,需要使用此源文件,编译才能成功。
extern "C" __declspec(dllexport) INT32 add(INT32 a, INT32 b)
{
    return (a + b);
}

 

2.2 客户端 c#
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CSharp调用c加加dll
{
    class Program
    {
        [DllImport("Dll1.dll")]
        public static extern int add(int a, int b);
        static void Main(string[] args)
        {
            int a = add(1, 2);
            Console.WriteLine(a);
            Console.ReadKey();
        }
    }
}

 

3.运行结果

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值