如何使用 COM 互操作将 C++ 结构传递给 C# DLL 方法

问题描述 投票:0回答:1

我当前有一个 C# 项目,该项目被编译成包含以下内容的 COM 互操作 DLL:

using System.Runtime.InteropServices;

namespace CommonTest
{
    [ComVisible(true)]
    public interface ICommonTest
    {
        [DispId(1)]
        int Test(int a, int b);
    }

    [ComVisible(true)]
    public class CommonTestManaged : ICommonTest
    {
        /// <summary>
        /// A method to test the creation of a managed DLL built in C#. It's functionality just adds together two numbers.
        /// </summary>
        /// <param name="a">Number 1</param>
        /// <param name="b">Number 2</param>
        /// <returns>The sum of numbers a and b</returns>
        public int Test(int a, int b)
        {
            return a + b;
        }
    }
}

在C++端,该方法被成功调用,如下所示:

void Usage()
{
    CoInitialize(nullptr);
    ICommonTestPtr pICommonTest(__uuidof(CommonTestManaged));

    long lResult = 0;
    pICommonTest->Test(5, 10, &lResult);

    CoUninitialize();
}

我的问题是,有没有办法将 C++ 结构作为 Test() 的参数传递,以便我可以在 C# 中访问其内容?

c# c++ com interop
1个回答
0
投票

这取决于结构体定义和类型(它必须可以由类型库描述),但是,是的,您可以在 C# 中创建这样的结构体

[ComVisible(true)]
[StructLayout(LayoutKind.Sequential)]
public struct Test
{
    public int Value1;
    public int Value2;
    etc...
}

在接口中像这样使用它(并在类中实现它):

[ComVisible(true)]
public interface ICommonTest
{
    void Test(ref Test test);
}

Visual Studio

#import
指令将在.tlh文件中生成如下代码:

struct __declspec(uuid("d80d27a3-7643-39bf-bba8-c8cc0ab10e7e"))
Test
{
    long Value1;
    long Value2;
    etc...
};

你可以在 C++ 中这样使用:

ICommonTestPtr pICommonTest(__uuidof(CommonTestManaged));

Test t = {};
t.Value2 = 123456789;
pICommonTest->Test(&t);
© www.soinside.com 2019 - 2024. All rights reserved.