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;
}
相关推荐
故事还在继续吗几秒前
C++内存模型
开发语言·c++·内存
Tairitsu_H2 分钟前
C++:构造函数与初始化列表详解
开发语言·c++·构造函数
琪露诺大湿7 分钟前
VeloQueue-测试报告
java·开发语言·消息队列·单元测试·项目·测试报告
minji...8 分钟前
Linux 网络套接字编程(四)支持多客户端同时在线、消息能转发给所有人的 UDP 聊天室服务器
linux·运维·开发语言·网络·c++·算法·udp
XS0301069 分钟前
Java 基础(十一)反射
java·开发语言
唐青枫11 分钟前
C#.NET MemoryMarshal 深入解析:零拷贝内存重解释、二进制读写与使用边界
c#·.net
t***54411 分钟前
Dev-C++中使用Clang调试有哪些常见错误
java·开发语言·c++
ydmy12 分钟前
强化学习/对齐(个人理解)
开发语言·python
一叶之秋141216 分钟前
哈希密钥:解锁unordered容器的极速潜能
开发语言·c++·哈希算法