C#生成dll给c++调用 方法二COM方式 vs2022 NO Make Assembly COM-Visible选错了 不需要clr

有些C++项目中也用了C语言.c,用方法一就无法使用【不能使用 /clr 选项编译 C 文件】。就用方法2。

方法二:COM方式

参考: https://www.5axxw.com/questions/content/2ozion

1.C# 生成dll

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Runtime.InteropServices;




namespace ClassLibrary1
{
    public class Class1
    {
        public interface IMyClass
        {
            void Initialize();
            void Dispose();
            int Add(int a, int b);
        }

        public class MyClass : IMyClass
        {
            public void Initialize()
            {

            }

            public void Dispose()
            {

            }

            public int Add(int a, int b)
            {
                return a + b;
            }
        }
    }
}

编译正常,C# dll就完成了。

2.C++调用示例

cs 复制代码
#include <iostream>
using namespace std;

#import "../x64/Debug/ClassLibrary1.tlb"

int main()
{
	CoInitialize(NULL); // 初始化com环境
	ClassLibrary1::IMyClassPtr p(__uuidof(ClassLibrary1::MyClass));
	cout << p->Add(3, 4) << endl;

	system("pause");
	return 0;
}
相关推荐
踏着七彩祥云的小丑7 小时前
pytest——Mark标记
开发语言·python·pytest
Dream of maid7 小时前
Python12(网络编程)
开发语言·网络·php
xiaoshuaishuai87 小时前
C# 接入 OpenClaw
windows·visualstudio·c#
W23035765737 小时前
经典算法:最长上升子序列(LIS)深度解析 C++ 实现
开发语言·c++·算法
Y4090017 小时前
【多线程】线程安全(1)
java·开发语言·jvm
不爱吃炸鸡柳8 小时前
Python入门第一课:零基础认识Python + 环境搭建 + 基础语法精讲
开发语言·python
minji...8 小时前
Linux 线程同步与互斥(三) 生产者消费者模型,基于阻塞队列的生产者消费者模型的代码实现
linux·运维·服务器·开发语言·网络·c++·算法
Dxy12393102168 小时前
Python基于BERT的上下文纠错详解
开发语言·python·bert
wjs202410 小时前
JavaScript 语句
开发语言