.Net互操作2

本文介绍如何使用C++创建一个动态链接库(DLL),并演示了如何在C#应用程序中调用该DLL中的函数。具体步骤包括创建C++项目、添加对外导出的函数、创建C#控制台应用以及实现跨语言调用。

1.C++创建Dll,Win32控制台,空项目,添加头文件NativeLib.h,NativeLib.cpp

extern "C" __declspec(dllexport) void __stdcall PrintMsg(const char* msg);
#include <stdio.h>
#include "NativeLib.h"


void __stdcall PrintMsg(const char* msg)
{
    printf("%s\n", msg);
    return;
}

2.C#创建控制台应用程序HelloWorld

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

namespace HelloWorld
{
    class Program
    {
        [DllImport("NativeLib.dll")]
        static extern void PrintMsg(string msg);
        static void Main(string[] args)
        {
            PrintMsg("Hello world!");
            Console.ReadLine();
        }
    }
}

3.修改C++项目属性:配置属性->连接器->常规->输出文件

修改C#项目属性:生成->输出->输出路径

两个输出路径要一致即可(eg:F:\试验\ex\Chapter 1\x86\Debug\NativeLib.dll(C++Dll输出文件),F:\试验\ex\Chapter 1\x86\Debug(C#输出路径))。

转载于:https://www.cnblogs.com/ccjcjc/p/3426017.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值