Question

forgive me if this has been answered before but I have not found a solution that works for me. I've seen many answers for passing a string from C# to C++ but not so many the other way around. Issue is I have a c++ application that needs to load a C# dll and pass it a string.

on the C# side of things I have this exposed through com.

namespace DriverCollect
{

    public interface IDriverInfo
    {

        int GetDriverInfo(ref string name);

    };


    public class DriverInterface:IDriverInfo
    {

        public int GetDriverInfo(ref string drivername)
        {
            DriverInfo myInfo = new DriverInfo(@"c:\logfile.txt") ;

            myInfo.Collect(drivername);
            return 0;
        }
    }
}

I have used regasm to register the tbl file and this is what I see in OLE type lib viewer

[
  odl,
  uuid(F3005FE7-DBA1-3FB6-807E-E66626EC875B),
  version(1.0),
  dual,
  oleautomation,
  custom(0F21F359-AB84-41E8-9A78-36D110E6D2F9, "DriverCollect.IDriverInfo")

]
interface IDriverInfo : IDispatch {
    [id(0x60020000)]
    HRESULT GetDriverInfo(
                    [in, out] BSTR* name, 
                    [out, retval] long* pRetVal);
};

on the C++ side of things this is my test case.

HRESULT hr = CoInitialize(NULL);

IDriverInfoPtr pDriverInfo(__uuidof(DriverInterface));

if(pDriverInfo)
   m_pDriverInfo = pDriverInfo;

BSTR s(L"c:\\xmltestdir\\cdromarm.sys");
long ret = 1;
hr = m_pDriverInfo->GetDriverInfo(&s,&ret);

CoUninitialize()

;

What happens is is that the BSTR is always empty when it is received by the C# dll. Other than that I get no errors, the ret value is changed when the function returns and the HRESULT is S_OK.
I have tried passing the BSTR by value also to the same effect.

Thoughts?

Was it helpful?

Solution

Your BSTR does not have a length prefix when you declare it so

BSTR s(L"c:\\xmltestdir\\cdromarm.sys");

Try declaring it so

BSTR s = SysAllocString(L"c:\\xmltestdir\\cdromarm.sys");

From here, If you pass a simple Unicode string as an argument to a COM function that is expecting a BSTR, the COM function will fail.

Also consider using CComBSTR or _bstr_t instead which manages the memory (allocating and freeing from the OLE heap) for you in case of exceptions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top