I'm trying to call a string function from a C# DLL that I made (to test COM out). I have a function called add which takes two ints and returns the sum. This seems to work. My other function, returnString, takes a string and returns it. This ends up printing out something blank. Here is the code:
C#:
public class Class1 : MyClass
{
public string returnString(string a)
{
return a;
}
public int add(int a, int b)
{
return a + b;
}
}
C++:
int main()
{
CoInitialize(NULL);
MyClassPtr obj;
obj.CreateInstance(__uuidof(Class1));
BSTR string_result = L"\0";
int int_result = 0;
HRESULT hr1 = obj->returnString(L"Hello", &string_result); // should set string_result to "Hello"
HRESULT hr2 = obj->add(5, 7, (long*)&int_result); // should set int_result to 12
if (hr1 != S_OK)
std::cout << "hr1: " << hr1 << std::endl;
else{
_bstr_t str(string_result);
std::cout << str << std::endl; // prints a blank line rather than "Hello"
}
if (hr2 != S_OK)
std::cout << "hr2: " << hr2 << std::endl;
else
std::cout << int_result << std::endl; // prints 12
CoUninitialize();
}
Here's what I get when I peak the definitions:
virtual HRESULT __stdcall returnString (
/*[in]*/ BSTR a,
/*[out,retval]*/ BSTR * pRetVal ) = 0;
virtual HRESULT __stdcall add (
/*[in]*/ long a,
/*[in]*/ long b,
/*[out,retval]*/ long * pRetVal ) = 0;
So what's wrong with the code? I posted a similar question recently and found out a little bit more, but I still cannot get it to behave properly. Thank you!
std::wcoutwhen printing unicode.