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;
}
相关推荐
星火开发设计1 分钟前
命名空间 namespace:解决命名冲突的利器
c语言·开发语言·c++·学习·算法·知识
小北方城市网1 分钟前
RabbitMQ 生产级实战:可靠性投递、高并发优化与问题排查
开发语言·分布式·python·缓存·性能优化·rabbitmq·ruby
爱学习的阿磊7 分钟前
C++中的策略模式应用
开发语言·c++·算法
郝学胜-神的一滴8 分钟前
Python中的bisect模块:优雅处理有序序列的艺术
开发语言·数据结构·python·程序人生·算法
Remember_99310 分钟前
Spring 事务深度解析:实现方式、隔离级别与传播机制全攻略
java·开发语言·数据库·后端·spring·leetcode·oracle
看得见的风13 分钟前
Claude Code + CCR配置(含OpenRouter、GLM、Kimi Coding Plan)
开发语言
L_090714 分钟前
【Linux】进程状态
linux·开发语言·c++
roman_日积跬步-终至千里15 分钟前
【Java并发】用 JMM 与 Happens-Before 解决多线程可见性与有序性问题
java·开发语言·spring
2401_8384725116 分钟前
C++异常处理最佳实践
开发语言·c++·算法
m0_7369191019 分钟前
C++中的类型标签分发
开发语言·c++·算法