简体   繁体   English

从C ++调用C#COM DLL

[英]Calling C# COM DLL from C++

The C++ code is as follows C ++代码如下

#include "stdafx.h"
#include <Windows.h>
#import "C:\shreyas\Documents\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.tlb" no_namespace

int _tmain(int argc, _TCHAR* argv[])
{

    CoInitialize(NULL);
    IMyClassPtr obj;

    //iProgramPtr obj;
    obj.CreateInstance(__uuidof(MyClass));
    printf("value: %d",obj->display());
    CoUninitialize();
    getchar();

    return 0;
}

The C# code is as follows C#代码如下

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

namespace demo
{
    [ComVisible(true)]
    public interface IMyClass
    {
        int display();
    }


    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    class MyClass : IMyClass
    {
        public int display()
        {
            Console.WriteLine("Hello");
            return 10;
        }
    }
}

I would like to call the C# display function from C++ code. 我想从C ++代码调用C#显示函数。 I have done the required settings in C# project properties. 我已经在C#项目属性中完成了所需的设置。 In the code obj.CreateInstance(__uuid(MyClass)); 在代码obj.CreateInstance(__uuid(MyClass)); the MyClass is giving an error as an undefined identifier. MyClass给出错误作为未定义的标识符。

Do pay attention to the build warning you get when you compile ConsoleApplication1: 请注意在编译ConsoleApplication1时收到的生成警告:

warning MSB3214: "C:...\\ConsoleApplication1\\bin\\Debug\\ConsoleApplication1.dll" does not contain any types that can be registered for COM Interop. 警告MSB3214:“ C:... \\ ConsoleApplication1 \\ bin \\ Debug \\ ConsoleApplication1.dll”不包含可以为COM Interop注册的任何类型。

That's not good of course. 那当然不好。 Also something you see with you look at the .tlb file with Oleview.exe's View + Typelib command. 使用Oleview.exe的View + Typelib命令查看.tlb文件时,还会看到一些内容。 Or open the .tlh file that the #import directive generates with a text editor, find it back in the C++ project's Debug directory. 或使用文本编辑器打开#import指令生成的.tlh文件,然后在C ++项目的Debug目录中找到它。 You'll see that MyClass is completely missing, thus the compile error. 您会看到MyClass完全丢失,因此出现编译错误。

That is because of: 这是因为:

   class MyClass : IMyClass

You forgot to declare it public . 您忘了宣布它为public Required. 需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM