互操作时COM接口的签名 [英] Signature of COM interface throught interop

查看:92
本文介绍了互操作时COM接口的签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从C#应用程序中的COM对象调用COM接口.

I need to call an COM interface from an COM object from my C# application.

我是从COM .dll生成的.tlh文件,该接口的定义如下:

ICertainInterface:IUnknown

ICertainInterface : IUnknown

{

  虚拟HRESULT __stdcall SetColors(

    virtual HRESULT __stdcall SetColors(

               b /* [in] */long cnt,

                        /*[in]*/ long cnt,

/* [in] */BSTR *颜色)= 0;

                       /*[in]*/ BSTR * colors) = 0;

}

我将此.dll添加到我的C#项目中,并且通过以下方式自动生成的C#签名:

I add this .dll to my C# project, and the C# signature auto generated is in this way:

公共接口ICertainInterface

public interface ICertainInterface

{

  无效SetColors(int cnt,ref字符串颜色);

    void SetColors(int cnt, ref string colors);

}

如果我尝试以这种方式调用接口:

And if I try to call the interface in this way:

string [] tmp =新字符串[3];

string[] tmp = new string[3];

tmp [0] ="aaa";

tmp[0] = "aaa";

tmp [1] ="bbb";

tmp[1] = "bbb";

tmp [2] ="ccc";

tmp[2] = "ccc";

ICertainInterface obj = GetObj();

ICertainInterface obj = GetObj();

obj.SetColors(3,ref tmp [0]);

obj.SetColors(3, ref tmp[0]);

将给出异常,例如尝试读取或写入受保护的存储器".但是,如果数组大小仅为1,则不会发生任何错误.在我看来,这是因为无法以C ++方式访问托管数组(使用第1个数组元素 代表阵列的地址).

An exception will be given say "Attempted to read or write protected memory". But if the array size is only 1, then no error occurred. This looks to me is because of the managed array can not accessed in C++ way (use 1st array element to stand for the array address).

对此有什么解决办法吗?

Is there any solution to this?

我想知道为什么C#签名会以参考字符串颜色"的形式为第二个参数生成?但不是"ref string []"?

And I wonder know, why the C# signature generate for the 2nd parameter in the form of "ref string colors" but not "ref string[]"?

推荐答案

BSTR *不是C数组,因此无法使用.实际上,这是对字符串的引用,这就是为什么按原样生成签名的原因.

BSTR* isn't a C-array so it won't work.  It is actually a ref to string which is why the signature is generated as it is.

您可以通过几种不同的方式来处理.第一种方法是 修改生成的签名以将其公开为字符串[].另一种方法是依靠数组在内存中的布局方式以及将字符串连接在一起的方式.为此,尽管您必须使用基础字节数组,然后 转换它.第一种方法是可取的.

You can handle this several different ways.  The first approach is to modify the generated signature to expose it as a string[].  The alternative approach is to rely on how arrays are laid out in memory and concat the strings together. For that to work though you'll have to work with the underlying byte array and then convert it.  The first approach is preferable.

迈克尔·泰勒
http://msmvps.com/blogs/p3net

Michael Taylor
http://msmvps.com/blogs/p3net


这篇关于互操作时COM接口的签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆