简体   繁体   English

通过ref将字符串传递给C#中的activex组件

[英]Passing string by ref to activex component in C#

I'm trying to us an ActiveX API function with the pattern function(ref string returnvalue) in C#. 我正在尝试为我们提供一个ActiveX API函数以及C#中的模式function(ref string returnvalue) The API function modifies the string. API函数修改字符串。

string returnValue = String.Empty;
api.func(ref returnValue); // DISP_E_TYPEMISMATCH

OK, maybe that's because strings are immutable. 好的,也许是因为字符串是不可变的。 Trying a StringBuilder per this : 为此尝试一个StringBuilder

StringBuilder returnValue = new StringBuilder(128);
api.func(returnValue);

This causes a compile-time error about type mismatch. 这会导致有关类型不匹配的编译时错误。

How do I call this function? 如何调用此功能?

I don't know if I need to marshal the C# string to a BStr, and if so, I don't know how to pass that by ref to the API function. 我不知道是否需要将C#字符串编组到BStr,如果是这样,我也不知道如何通过ref传递给API函数。

If func should change returnValue , I think your code should be changed like this: 如果func应该更改returnValue ,我认为您的代码应该像这样更改:

string returnValue = String.Empty;
api.func(ref returnValue);

You should init returnValue before pass it by ref . 您应该先将returnValue初始化为ref,然后再将其传递。

UPD: Did you try to call it like this?: UPD:您是否尝试过这样称呼它:

api.func(ref Marshal.StringToBSTR(string value));

Call it with a reference to a string variable, as it says: 如对它所说的那样,引用一个string变量:

string returnValue = "";
api.func(ref returnValue);

You might want to take a look at the ref and out keywords in C#. 您可能想看看C#中的refout关键字。

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

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