C#下分别调用C++/C#生成的dll文件

1、C#下分别调用C++生成的dll文件

第一步,新建项目

选择 Win32控制台应用程序或者Win32项目均可

点击“确定”后,选择DLL 和 空项目,点击“完成”

添加文件“MyDll.h” “MyDll.cpp”

#pragma once

#define EXEAPI extern "C" __declspec(dllexport) // C方式导出函数
EXEAPI int AddValue(int x, int y);
#include "MyDll.h"
#include <stdlib.h>

//求两个值得和   
int AddValue(int x,int y)
{
	return x + y;
}

编译生成 Win32Dll.dll

第二步 重新建立C# win32 项目 MyDllDemo ,添加新类class DllTest

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

namespace MyDllDemo
{
    class DllTest
    {
        const string dllpathfile = "Win32Dll.dll";
        
        [DllImport(dllpathfile, EntryPoint = "AddValue", CallingConvention = CallingConvention.Cdecl)]
        public static extern int AddValue(int x, int y); 
    }
}

class Program 中调用

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

namespace MyDllDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int result = DllTest.AddValue(2, 3);
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

编译运行

2、C#下分别调用C#生成的dll文件

第一步,建立C#类库CSharpClassLib,建立新类 TestClass

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

namespace CSharpClassLib
{
    public class TestClass
    {
        public  void Hello()
        {
            Console.WriteLine("Hello World!");
        } 
    }
}

第二步,上述编译生成CSharpClassLib.dll,将其拷贝到MyDllDemo 项目的debug的bin下,然后在MyDllDemo 项目下添加 “引用”,将此dll引用。

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

namespace MyDllDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            TestClass test = new TestClass();
            test.Hello();
            Console.ReadKey();
        }
    }
}

第三步,编译执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值