0

I have a C# Class Library which is COM visible and being called from a Visual Studio 6 application. One of the methods needs to return a string. I have tried this two ways:

public void GetString(out string sText)
{
    sText = MemberStringVariable;
}

When I call the above from VC6 I get an exception thrown.

public string GetString()
{
    return MemberStringVariable;
}

When I call the above (taking a BSTR* as parameter) I get a NULL pointer back.

What is the proper way of doing this?

Jonnster
  • 3,094
  • 5
  • 33
  • 45
  • 1
    The 2nd way is correct. Getting a null BSTR* would indicate that MemberStringVariable is simply unassigned. Use the debugger in mixed mode so you can set a breakpoint in the C# code. – Hans Passant Jul 13 '12 at 16:25

3 Answers3

0

Your second method:

public string GetString() { return MemberStringVariable; }

Should work. I do it all the time. The type you get in C++ is _bstr_t as defined in comutil.h

edeboursetty
  • 5,669
  • 2
  • 40
  • 67
  • It's not though, it's a NULL BSTR* pointer I get back. Do I need to allocate the string on the client end? This would seem odd as I would expect it to be allocated the other end. Afterall I have no idea how long the string would be. – Jonnster Jul 13 '12 at 16:08
  • @Joonster: can you generate the tlb with tlbexport and post the signature (using OLEView)? The signature of my methods are like `[id(0x60020007)] HRESULT get_Stuff([in] BSTR arg1, [out, retval] BSTR* pRetVal);` – edeboursetty Jul 13 '12 at 17:15
  • Also, you need to make sure your dll is properly registered with COM – edeboursetty Jul 13 '12 at 17:16
  • And that you don't have any incompability between 32 and 64 bits – edeboursetty Jul 13 '12 at 17:17
  • Perhaps this is the issue. The class library is built on a 64 bit machine. The configuration is "Any CPU" though. The client app is 32-bit. Is this the problem? – Jonnster Jul 16 '12 at 09:06
  • @Jonnster: Try using the x86 configuration. I don't think this is the issue, but it doesn't hurt to try. It would help if you could pull out the idl from the C# dll with tlbexp. – edeboursetty Jul 17 '12 at 20:39
0

See this question and answer. I'm doubtful you can just return a string to the native code.

Community
  • 1
  • 1
user845279
  • 2,794
  • 1
  • 20
  • 38
0

Oh, it's been a while since I did COM interop, but I seem to recall you may need to use the MarshalAsAttribute on your method's return value.

[return: MarshalAs(UnmanagedType.Bstr)]
public string GetString() 
{ 
    return MemberStringVariable; 
} 

For more examples, see http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute(v=vs.100).aspx.

Monroe Thomas
  • 4,962
  • 1
  • 17
  • 21