0

I have c++ code that has a parameter like this:

STDMETHODIMP TVinaImpl::test(BSTR Param1)
{
  try
  {
      Param1=(L"test1");
  }
  catch(Exception &e)
  {
    return Error(e.Message.c_str(), IID_IVina);
  }
  return S_OK;
}  

I use c++ builder:
enter image description here
When I call this com dll function in c# it shows me the error:

IntPtr a = new IntPtr();
vina.test(a);

it is null and did not get the value.
How can I pass variable from C# to c++ com and pass back it?

0

2 Answers 2

2

Since Param1 is declared as an [in, out] parameter, you need to declare it as a pointer to a BSTR: STDMETHODIMP TVinaImpl::test(BSTR* Param1)

Furthermore, you cannot simply assign a string literal to a BSTR. The correct way is to allocate memory using SysAllocString: *Param1 = SysAllocString(L"test1");

Sign up to request clarification or add additional context in comments.

4 Comments

If there any way to avoid using SysAllocString in c++?
Unfortunately that's not possible. BSTRs are managed by COM and always need to be allocated from its memory allocator. If automation compatibility is not required, you might consider using a simple wchar_t* instead.
Is there any way to allocate memory in client side (for example in c# ) and pass parameter by reference to c++ method?
Yes, that's possible. You will need to change your definition of Param1 to wchar_t*, as indicated in my previous comment: [in, out, string] wchar_t** Param1.
0

I'd recommend you declare the argument Param1 as [out, retval]. You are not using Param1 as any kind of input.

STDMETHODIMP TVinaImpl::test(BSTR* Param1)
{
  try
  {
      *Param1= SysAllocString(L"test1");
  }
  catch(Exception &e)
  {
    return Error(e.Message.c_str(), IID_IVina);
  }
  return S_OK;
}  

Then when you call the function from C# it is just,

string s = vina.test();

The .Net runtime manages marshalling of data from .Net to COM and vice versa.

1 Comment

You said right, but when I want return multi parameters to send my function and return all of them, How can I do that. each function just can get one return value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.