简体   繁体   中英

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#. The API function modifies the string.

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 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.

If func should change returnValue , I think your code should be changed like this:

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

You should init returnValue before pass it by ref .

UPD: Did you try to call it like this?:

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

Call it with a reference to a string variable, as it says:

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

You might want to take a look at the ref and out keywords in C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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