Using C ++ Component Object Model in C #

I am trying to create a C ++ COM library using a C # project for testing. Some methods must return rows to the caller. When calling these methods from C #, I get the following: "Read access violation in place ..."

This is the C ++ code from my test project (in addition to everything that VS ATL created).

//COMTest.idl
[id(1)] HRESULT Test([out,retval] BSTR* ret);

//Program2.h
STDMETHOD(Test)(BSTR* ret);

//Program2.cpp
STDMETHODIMP CProgram2::Test(BSTR* ret)
{
   BSTR tmp = (BSTR)CoTaskMemAlloc(sizeof(wchar_t) * 2);
   tmp[0] = L'H';
   tmp[1] = L'\0';

   *ret = (BSTR)tmp;
   return S_OK;
}


In C #, I just referenced the DLL from COM-Tab, turned off "Insert Interrupt Types" because it caused errors and ran this:

static void Main(string[] args)
{
   COMTestLib.Program2Class instance = new COMTestLib.Program2Class();
   string tmp = instance.Test(); //Where the error occurs

   Console.WriteLine(tmp); //This is not reached

   Console.Read();
}

The error occurs after exiting the test method. I debugged C ++ code from my C # project and the values ​​were placed in the right places. I do not get an error if I try to return 0 (gives null in C #), even if I still allocate memory, as in the example.

, . , , - , . , CoTaskMemAlloc , (0x00XXXXXX), COM.


, ( COM) . - ?

+5
2

BSTR ( len), BSTR ( : SysAllocString() "" BSTR).

, :

//Program2.cpp
STDMETHODIMP CProgram2::Test(BSTR* ret)
{
   *ret = SysAllocString(L"H");
   return S_OK;
}

BSTR: http://blogs.msdn.com/b/ericlippert/archive/2003/09/12/52976.aspx

+3

, COM STA. . , BSTR LPSTR?

0

All Articles