C#调用C++ 动态链接库dll

xiaotu123 · 2022-12-21 11:29:03 · 2210 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    
这是一个创建于 2022-12-21 11:29:03 的文章,其中的信息可能已经有所发展或是发生改变。

在过程中发现两种方法解决问题:一种是非托管C++创建的dll库,需要用静态方法调用。这种方法无法在C#的reference中直接引用,而是要用静态调用的方法, 其他博客已经介绍的很详尽,唯一需要补充的是,C#文件需要先:

using System.Runtime.InteropServices;

之后才可以调用[DllImport]方法。 另一种方法是直接使用CLR,生成托管C++dll库。 创建流程 例程如下 C++ dll:

// CPPlibdemo.h
#pragma once

using namespace System;


namespace CPPlibdemo {

    public ref class Class1
    {
        // TODO: Add your methods for this class here.
    public:
            String ^getgreating(){

            return "hello world";
        }
    };
}

C#语言:

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

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            Class1 clrdemo = new Class1();


            Console.Write(clrdemo.getgreating());
            Console.ReadLine();
        }
    }
}

有疑问加站长微信联系(非本文作者))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2210 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传