I make an OCX in C++ Builder Borland. My OCX has these function as I describe it:
Login
Write
Read
DebugOutput
GetVal
I am using this OCX in my c# application. In c# side I have a button and list box. The button calls login method from OCX and the list box shows this method's output.
In OCX side, the login method creates a command for server (with socket programming) to get authentication. Then call Write function to writes on socket. Then gets response from socket and calls Read function to reads the socket response.
The Read method reading the result and send it to DebugOutput to debug the output stream and call GetVal to find Last main server response. Then they pass their parameters to each other. after all the C# side show the result (SUCCESS | FAIL ) for login methods.
I used BSTR. (I read the topics about BSTR in stackoverflow and on MSDN but I think I did not get it well in my solution). These are my code in OCX side:
BSTR STDMETHODCALLTYPE TVImpl::Login(BSTR PassWord)
{
wchar_t wcs1[500];
Var *var=new Var();
//here make the command
...................
//get the server response to show to user
BSTR read=::SysAllocString(Write(wcs1));
if(read!=NULL) ::SysFreeString(read);
return read;
}
BSTR STDMETHODCALLTYPE TVImpl::Read()
{
BSTR str ;
try
{
IdTCPClient1->ReadTimeout=100;
str =::SysAllocString( IdTCPClient1->IOHandler->ReadLn().c_str());
}
catch(Exception &e)
{
str= e.Message.c_str();
}
str=(DebugOutput(str));
return str;
}
BSTR STDMETHODCALLTYPE TVImpl::Write(BSTR str)
{
IdTCPClient1->IOHandler->WriteLn(str) ;
BSTR str2=::SysAllocString(L"TST");
str2=Read();
return str2;
}
BSTR STDMETHODCALLTYPE TVImpl::GetVal(BSTR st,BSTR ValTyp)
{
BSTR res;
AnsiString stAnsi;
//Do some thing with st and save it to stAnsi
.................
res=(BSTR)WideString(stAnsi);
return ::SysAllocString(res);
}
BSTR STDMETHODCALLTYPE TVImpl::DebugOutput(BSTR st)
{
Var *val=new Var();
BSTR res;
res=GetVal(st,val->CMD_CMD);
if(res==val->CMD_AUTHENTICATE)
res=GetVal(st,val->XPassword);
return res;
}
In C3 code it was hanging. I know my problem is to use sysAllocString. but I when I used ::sysFreestring for each one in each method again my C# code hanging.
This is my C# code :
private void button4_Click(object sender, EventArgs e)
{
VinSockCmplt.Vin vin = new Vin();
listBox1.Items.Add(vin.Login("1234"));
}
You should not return BSTR (or any "complex" type that various compilers compile in various ways). The recommended return type for COM methods is HRESULT (a 32-bit integer). Also, you must not release a BSTR you just allocated and return it to the caller.
Here is how you could layout your methods:
HRESULT STDMETHODCALLTYPE TVImpl::Login(BSTR PassWord, /*out*/ BSTR *pRead)
{
...
*pRead = ::SysAllocString(L"blabla"); // allocate a BSTR
...
// don't SysFreeString here, the caller should do it
...
return S_OK;
}
If you were defining your interface in a .idl file, it would be something like:
interface IMyInterface : IUnknown
{
...
HRESULT Login([in] BSTR PassWord, [out, retval] BSTR *pRead);
...
}
retval is used to indicate assignment semantics are possible for languages that support it, like what you were trying to achieve initially with code like this var read = obj.Login("mypass")
There are lots of mistakes in your code:
if(read!=NULL) ::SysFreeString(read); return read; frees a string and then returns it
str= e.Message.c_str(); ... return str; returns a pointer to something that isn't even a BSTR
BSTR str2=::SysAllocString(L"TST"); str2=Read(); allocates a string and then leaks that string immediately
res=(BSTR)WideString(stAnsi); creates a dangling pointer
All of these are undefined behaviour (except the leak) and might cause a crash.
Also, I'm not sure if it is valid to have your functions return BSTR; the normal convention in COM programming is that functions return HRESULT and any "return values" go back via [out] parameters. This is compatible with all languages that have COM bindings; whereas actually returning BSTR limits your code compatibility. (I could be wrong - would welcome corrections here). You can see this technique used in the other question you linked.
To get help with a question like "Why is my code crashing?", see How to Ask and How to create a Minimal, Complete, and Verifiable example.
Related
Let me start off by saying that VB is not my strong suit.
I am developing a C++ dll to be used in a VB6 application's dll.
I have successfully instantiated the (C++) classes in VB. I am trying to access data members of the class using this syntax: "vbCppObj.dataMemberName".
I can confirm that this works for boolean and enum types and it invokes the getter methods defined in my class.
I have to access a string from the (C++) class as well.
The getter function for the string is given below:
class MyCPPClass
{
private:
WCHAR* CPPErrorString = L"This is a string";
public:
HRESULT __stdcall get_CPPErrorString(BSTR* pVal)
{
BSTR str = ::SysAllocString(CPPErrorString);
if(str)
*pVal = str;
return S_OK;
}
};
I am unable to debug the C++ dll right now.
I access this value in the VB6 code as follows:
ErrorString = vbCppObj.CPPErrorString
Logger.log "[Log]:" & ErrorString
"ErrorString" is a String type in VB. When this line executes, the "ErrorString" object shows "<Out of memory>" (when I hover over it). If I step further, to the logging code, it gives me a "Error 14: Out of string space".
Also, I have typed this code in the browser so, it may not be 100% correct.
As it turns out, I had to convert the string into a "_b_str" and then to a "BSTR". That worked for me.
I had tried it earlier but I don't know why it didn't work at that time.
Why you just don't use LPCTSTR?
I'm not an advanced C/C++ programmer, but this should work
class MyCPPClass
{
private:
LPCTSTR CPPErrorString = "This is a string";
public:
HRESULT __stdcall get_CPPErrorString(LPCTSTR * pVal)
{
// copy the value
*pVal = CPPErrorString;
// return
return S_OK;
}
}
We have a COM API for our application (which is written in VC++) which exposes a few functionalities so that the users can automate their tasks. Now, I'm required to add a new method in that, which should return a list/array/vector of strings. Since I'm new to COM, I was looking at the existing methods in the .idl file for that interface.
One of the existing methods in that idl file looks like this:
interface ITestApp : IDispatch
{
//other methods ..
//...
//...
//...
[id(110), helpstring("method GetFileName")] HRESULT GetFileName([out, retval] BSTR *pFileName);
//...
//...
//...
};
My task is to write a similar new method, but instead of returning one BSTR string, it should return a list/array/vector of them.
How can I do that?
Thanks!
Since yours is an automation-compatible interface, you need to use safearrays. Would go something like this:
// IDL definition
[id(42)]
HRESULT GetNames([out, retval] SAFEARRAY(BSTR)* names);
// C++ implementation
STDMETHODIMP MyCOMObject::GetNames(SAFEARRAY** names) {
if (!names) return E_POINTER;
SAFEARRAY* psa = SafeArrayCreateVector(VT_BSTR, 0, 2);
BSTR* content = NULL;
SafeArrayAccessData(psa, (void**)&content);
content[0] = SysAllocString(L"hello");
content[1] = SysAllocString(L"world");
SafeArrayUnaccessData(psa);
*names = psa;
return S_OK;
}
Error handling is left as an exercise for the reader.
From book ATL Internals, I knew BSTR is different from OLECHAR*, and there are CComBSTR and CString for BSTR.
According MSDN Allocating and Releasing Memory for a BSTR, I knew memory management responsibility for caller/callee.
Take this line from MSDN,
HRESULT CMyWebBrowser::put_StatusText(BSTR bstr)
I still do not know how to handle bstr properly in my implementation. Since I still have a basic question for BSTR -- should we treat bstr as a value (like int) or as a reference (like int*), at least on COM interface boundary.
I want to convert BSTR as soon as possible to CString/CComBSTR in my implementation. Value or Reference semantic will be totally different case for the conversion. I've digged into CComBSTR.Attach, CComBSTR.AssignBSTR, etc. But the code cannot solve my doubts.
MSDN CComBSTR.Attach has some code snip, I feel it is wrong since it is not obey Allocating and Releasing Memory for a BSTR. ATL Internals said SetSysString will 'free the original BSTR passed in', if I used it, it will violate BSTR argument convention, just like CComBSTR.Attach.
All in all, I want to using CString to handle raw BSTR in implementation, but do not know the correct way...I've written some just work code in my projects, but I always feel nervous since I don't know whether I am correct.
Let me talk coding language
HRESULT CMyWebBrowser::put_StatusText(BSTR bstr)
{
// What I do NOT know
CString str1; // 1. copy bstr (with embeded NUL)
CString str2; // 2. ref bstr
// What I know
CComBSTR cbstr1;
cbstr1.AssignBSTR(bstr); // 3. copy bstr
CComBSTR cbstr2;
cbstr2.Attach(bstr); // 4. ref bstr, do not copy
// What I do NOT know
// Should we copy or ref bstr ???
}
CComBSTR is just a RAII wrapper around raw BSTR. So feel free to use CComBSTR instead of raw BSTR to help writing code that is exception-safe, that makes it harder to leak resources (i.e. the raw BSTR), etc.
If the BSTR is an input parameter, it's just like a const wchar_t* (with length prefixed, and potentially some NULs L'\0' characters inside). If the BSTR doesn't have NULs embedded inside, you can simply pass it to a CString constructor, that will make a deep-copy of it, and you can locally work with your CString. Modifications to that CString won't be visible on the original BSTR. You can use std::wstring as well (and note that std::wstring can handle embedded NULs as well).
void DoSomething(BSTR bstrInput)
{
std::wstring myString(bstrInput);
// ... work with std::wstring (or CString...) inside here
}
Instead, if the BSTR is an output parameter, then it is passed using another level of indirection, i.e. BSTR*. In this case, you can use CComBSTR::Detach() inside your method to release the BSTR safely wrapped into the CComBSTR, and transfer its ownership to the caller:
HRESULT DoSomething( BSTR* pbstrOut )
{
// Check parameter pointer
if (pbstrOut == nullptr)
return E_POINTER;
// Guard code with try-catch, since exceptions can't cross COM module boundaries.
try
{
std::wstring someString;
// ... work with std::wstring (or CString...) inside here
// Build a BSTR from the ordinary string
CComBSTR bstr(someString.c_str());
// Return to caller ("move semantics", i.e. transfer ownership
// from current CComBSTR to the caller)
*pbstrOut = bstr.Detach();
// All right
return S_OK;
}
catch(const std::exception& e)
{
// Log exception message...
return E_FAIL;
}
catch(const CAtlException& e)
{
return e; // implicit cast to HRESULT
}
}
Basically, the idea is to use BSTR (wrapped in a RAII class like CComBSTR) only at the boundary, and do the local work using std::wstring or CString.
As a "bouns reading", consider Eric Lippert's guide to BSTR semantics.
Having BSTR on input, you are not responsible to release it. Converting to CString is easy:
CString sValue(bstr);
or, if you prefer to keep Unicode characters on MBCS build:
CStringW sValue(bstr);
If you need to convert back when you have [out] parameter, you do (simple version):
VOID Foo(/*[out]*/ BSTR* psValue)
{
CString sValue;
*psValue = CComBSTR(sValue).Detach();
}
Full version is:
STDMETHODIMP Foo(/*[out]*/ BSTR* psValue)
{
_ATLTRY
{
ATLENSURE_THROW(psValue, E_POINTER); // Parameter validation
*psValue = NULL; // We're responsible to initialize this no matter what
CString sValue;
// Doing our stuff to get the string value into variable
*psValue = CComBSTR(sValue).Detach();
}
_ATLCATCH(Exception)
{
return Exception;
}
return S_OK;
}
What is the correct way of doing this:
_bstr_t description;
errorInfo->GetDescription( &description.GetBSTR() );
or:
_bstr_t description;
errorInfo->GetDescription( description.GetAddress() );
Where IError:GetDescription is defined as:
HRESULT GetDescription (BSTR *pbstrDescription);
I know I could easily do this:
BSTR description= SysAllocString (L"Whateva"));
errorInfo->GetDescription (&description);
SysFreeString (description);
Thanks
The BSTR is reference counted, I seriously doubt that will work right if you use GetAddress(). Sadly the source code isn't available to double-check that. I've always done it like this:
BSTR temp = 0;
HRESULT hr = p->GetDescription(&temp);
if (SUCCEEDED(hr)) {
_bstr_t wrap(temp, FALSE);
// etc..
}
To follow up on #Hans's answer - the appropriate way to construct the _bstr_t depends on whether GetDescription returns you a BSTR that you own, or one that references memory you don't have to free.
The goal here is to minimize the number of copies, but also avoid any manual calls to SysFreeString on the returned data. I would modify the code as shown to clarify this:
BSTR temp = 0;
HRESULT hr = p->GetDescription(&temp);
if (SUCCEEDED(hr)) {
_bstr_t wrap(temp, false); // do not copy returned BSTR, which
// will be freed when wrap goes out of scope.
// Use true if you want a copy.
// etc..
}
A late answer that may not apply to earlier (or later) versions of Visual Studio; however,
VS 12.0 has the _bstr_t implementation inline, and evidently an internal Data_t instance is created with a m_RefCount of 1 when calling GetBSTR() on a virgin _bstr_t. So the _bstr_t lifecycle in your first example looks to be okay:
_bstr_t description;
errorInfo->GetDescription( &description.GetBSTR() );
But if _bstr_t is dirty, the existing internal m_wstr pointer will be overwritten, leaking the previous memory it referenced.
By using the following operator&, a dirty _bstr_t can be used given that it's first cleared via Assign(nullptr). The overload also provides the convenience of utilizing the address operator instead of GetBSTR();
BSTR *operator&(_bstr_t &b) {
b.Assign(nullptr);
return &b.GetBSTR();
}
So, your first example could instead look like the following:
_bstr_t description(L"naughty");
errorInfo->GetDescription(&description);
This evaluation was based on comutil.h from VS 12.0.
_bstr_t (and its ATL sibling CComBSTR) are resource owners of BSTR. Spying from the code it seems that 'GetAddress' is specifically designed for the use case of working with BSTR output parameters where it is expected that client frees the BSTR.
Using 'GetAddress()' is not equivalent to using '&GetBSTR()' in case the _bstr_t already owns a BSTR. MSDN states: 'Frees any existing string and returns the address of a newly allocated string.'.
_bstr_t bstrTemp;
HRESULT hr = p->GetDescription(bstrTemp.GetAddress());
Caveat: this specific use case of 'GetAddress' is not stated in the documentation; it is my deduction from looking at the source code and experience with its ATL counter part CComBSTR.
Since user 'caoanan' questioned this solution, I paste here the source code Microsoft:
inline BSTR* _bstr_t::GetAddress()
{
Attach(0);
return &m_Data->GetWString();
}
inline wchar_t*& _bstr_t::Data_t::GetWString() throw()
{
return m_wstr;
}
inline void _bstr_t::Attach(BSTR s)
{
_Free();
m_Data = new Data_t(s, FALSE);
if (m_Data == NULL) {
_com_issue_error(E_OUTOFMEMORY);
}
}
inline _bstr_t::Data_t::Data_t(BSTR bstr, bool fCopy)
: m_str(NULL), m_RefCount(1)
{
if (fCopy && bstr != NULL) {
m_wstr = ::SysAllocStringByteLen(reinterpret_cast<char*>(bstr),
::SysStringByteLen(bstr));
if (m_wstr == NULL) {
_com_issue_error(E_OUTOFMEMORY);
}
}
else {
m_wstr = bstr;
}
}
My answer is also late. Suppose you have the signature HRESULT PutDescription (BSTR NewDescription);. In that case do the following
_bstr_t NewAdvice = L"Great advice!";
HRESULT hr1 = PutDescription(NewAdvice.GetBSTR());
By the rules of COM, the function PutDescription is not allowed to change or even destroy the passed BSTR.
For the opposite HRESULT GetDescription (BSTR *pActualDescription); pass a virgin _bstr_t by means of the function GetAddress():
_bstr_t GetAdvice;
HRESULT hr2 = GetDescription(GetAdvice.GetAddress());
The function GetAddress() frees any existing string and returns the address of a newly allocated string. So, if you pass a _bstr_t that has some content, this content will be freed and is therefore lost. The same happens to all _bstr_ts that share the same BSTR. But I think this is a stupid thing to do. Why passing an argument with content to a function that is supposed to change that content?
_bstr_t GetAdvice = L"This content will not survive the next function call!";
HRESULT hr = GetDescription(GetAdvice.GetAddress());
A real moron might even pass a _bstr_t that is assigned to a raw BSTR:
BSTR Bst = ::SysAllocString(L"Who would do that?");
_bstr_t GetDescr;
GetDescr.Attach(Bst);//GetDescr wraps Bst, no copying!
HRESULT hr = GetDescription(GetDescr.GetAddress());
In that case GetDescr gets the expected value but the content of Bst is unpredictable.
int GetDataStr(_bstr_t & str) override {
BSTR data = str.Detach();
int res = m_connection->GetDataStr( &data );
str.Attach(data);
return res;
}
I am using this code to sink events in a IWebBrowser2 webbrowser on c++:
STDMETHODIMP AdviseSink::Invoke(DISPID dispIdMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS* pDispParams,
VARIANT* pVarResult,
EXCEPINFO* pExcepInfo,
UINT* puArgErr)
{
if (!pDispParams)
return DISP_E_PARAMNOTOPTIONAL;
switch (dispIdMember)
{
case DISPID_DOCUMENTCOMPLETE:
{
DocumentComplete(pVarResult);
return S_OK;
}
case DISPID_NAVIGATECOMPLETE2:
return S_OK;
default:
return DISP_E_MEMBERNOTFOUND;
}
return S_OK;
}
void DocumentComplete(VARIANT *url)
{
std::string strValue = (char*)_bstr_t(url);
}
When calling (void)DocumentComplete I get this error:
*Unhandled exception at 0x7c812afb in webhost.exe: Microsoft C++ exception: _com_error at memory location 0x0012ed50.*
If comment the line on DocumentComplete, it doesn't show any errors. Also try..catch blocks doens't catch the exception.
What I am trying to do is to use Variant * url to compare it with a std::string.
How can I do this?
You are using the return value (an [out] parameter) as one of the event parameters. This will cause bstr_t to throw a com_error exception because the VARIANT doesn't contain a BSTR.
See the MSDN documentation for the correct DocumentComplete signature.
The event parameters are available from pDispParams not pVarResult. Assuming that it's not called with named arguments (and this event shouldn't be), the url will be available at pDispParams->rgvarg[0] and the window/frame at pDispParams->rgvarg[1]. Parameters are in the opposite order in the rgvarg array as they're declared in the idl.
If you can, I recommend instead using ATL's IDispEventSimpleImpl to implement COM event interfaces in C++ instead of implementing IDispatch yourself.
http://msdn.microsoft.com/en-us/library/9k3ebasf(v=VS.100).aspx
the _bstr_t constructor takes only reference of VARIANT, instead of pointer to it.
YeenFei gave half of the answer. The other half is that after you get your bstr, it will point to a Unicode string not to an ANSI string. If you want to get an ANSI string, you have to do it by converting the string from Unicode to ANSI, not by converting the pointer.