简体   繁体   中英

How would I call a legacy C++ DLL interface method, with params BSTR* and BSTR** from C#

Good Day fellow developers

I have been searching the internet for 2 days now on how to do what I need and I have tried a lot of samples with no success. However, that does not mean I covered all sites - I am thinking I am blind in one eye and cannot see out the other.

At any rate, I was handed a single sheet of paper with a COM Automation Interface definition on it and was asked to develop a C# application to utilize the interface and the callbacks accordingly.

So, starting simple (or so I thought) - the C++ method signature is:

STDMETHODIMP CSimpleChatServer::CallMe(BSTR clientName, BSTR** returnMessage)

and the interface signature is:

HRESULT _stdcall CallMe([in] BSTR clientName, [in] BSTR** helloMessage);

And I need to call this from C# - I have established the Interface for ISimpleChatServer; hence, the code call I am trying is like.

string rtrnMsg = string.Empty; ImySimpleCom.CallMe("Robert", rtrnMsg)

Since the signature is an [in], I am getting an exception on trying to access protected memory.

Now, I believe it wants an IntPtr as the second parameter; however, all my attempts to get that to be taken have failed.

Please keep in mind that I am not able to change the library - it is an "As Is" legacy interface that we need to utilize for a little while longer and the provider has nobody to update it accordingly (in fact I think they do not have anyone to work on it).

Any help would be kindly welcomed.

Kind Regards, Robert S.

In the .idl the interface should be

HRESULT _stdcall CallMe([in] BSTR clientName, 
                        [out,retval] BSTR** helloMessage);

So just take the return value from CallMe

SimpleChatServer mySimpleCom = new SimpleChatServer();   
string helloMessage = mySimpleCom( clientName );

When you return the string in C++/C method you allocate using SysAllocString and return that to caller by assigning to helloMessage.

ie

*helloMessage = SysAllocString(L"MyString");

All the above assumes that you have referenced the COM server in your C# project.

I read your question more carefully now, so you cannot change the "legacy" code? if it says

HRESULT _stdcall CallMe([in] BSTR clientName, 
                        [in] BSTR** helloMessage);

Then it should be changed because that is not correct.

Thanks All and Andres

I finally got in touch with the client and yes, the information they provided was incorrect and the [in] attribute was supposed to be [out,retval] to allow for the passing back of the string - once they corrected that, all went fine.

Great appreciation to all - Thank You

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