Hello,
Example from C++ side:
interface declaration
interface ISampleInterface:public IUnknown
{
STDMETHOD(put_Value)(BSTR _value) = 0;
STDMETHOD(get_Value)(BSTR * _value) = 0;
};
Class example which provide that functionality:
class CTest : public ISampleInterface
{
private:
WCHAR m_szString[1024];
public:
CTest() {wcscpy_s(m_szString,L"");}
public:
STDMETHODIMP put_Value(BSTR _value);
{
if (!_value || !wcslen(_value)) return E_INVALIDARG;
wcscpy_s(m_szString,_value);
return NOERROR;
}
STDMETHODIMP get_Value(BSTR * _value)
{
if (!_value) return E_INVALIDARG;
*_value = SysAllocString(m_szString);
return NOERROR;
}
};
Example on C# side with specify marshaling type:
Here is type specified so .NET will do marshaling stuff in RCW.
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISampleInterface
{
[PreserveSig]
int put_Value([In, MarshalAs(UnmanagedType.BStr)] string _value);
[PreserveSig]
int get_Value([Out, MarshalAs(UnmanagedType.BStr)] out string _value);
}
Example on C# side without marshaling:
Here you directly perform marshaling type.
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISampleInterface
{
[PreserveSig]
int put_Value(IntPtr _value);
[PreserveSig]
int get_Value(out IntPtr _value);
}
For such declaration you should have code:
ISampleInterface _sample;
{
IntPtr _ptr = Marshal.StringToBSTR("some string");
_sample.put_Value(_ptr);
Marshal.FreeBSTR(_ptr);
}
{
IntPtr _ptr;
_sample.get_Value(out _ptr);
string _result = Marshal.PtrToStringBSTR(_ptr);
Marshal.FreeBSTR(_ptr);
}
Regards,
Maxim.